How to receive signed integer through socket

5 次查看(过去 30 天)
Hi, I need Mathlab to receive integer values from a system for testing several data filters. I have written the server code in mathlab and the client code that sends the integer values in the system. The connection is established and data is sent and received, but mathlab has problems interpreting the received values.
For example, if a send integer -40, mathlab reads it and interpret it as -620756993
I guess it is just a data type problem, but I am new in mathlab world, and have no idea about how to get the correct values.
This is the Mathlab script I am using:
clear
tcpipServer = tcpip('0.0.0.0', 8181, 'NetworkRole', 'Server');
set(tcpipServer, 'InputBufferSize', 1024);
fopen(tcpipServer);
while true
rawData = fread(tcpipServer,1,'int32');
rawData % this line shows the wrong value
end
Any help will be appreciated!
Thanks

采纳的回答

Walter Roberson
Walter Roberson 2017-6-3
The server is probably sending in Network Byte Order, which is "big endian". All current versions of MATLAB are "little endian".
You can configure ByteOrder for the entire TCP connection, or you can read the way you are and then swap bytes
>> A = int32(-620756993)
A =
int32
-620756993
>> swapbytes(A)
ans =
int32
-38
However, if you are reading -620756993 for -40 then the sending system is not using any standard numeric encoding. -40 is FFFFFFD8 in two's complement, or FFFFFFD7 in 1's complement, and -620756993 is DAFFFFFF . You can see how the FF bytes might potentially be swapped around, but the DA byte of -620756993 cannot be matched anywhere in FFFFFFD8 or FFFFFFD7 . Is it possible that you were mistaken about it being -40 that corresponds to -620756993 ?
  1 个评论
Javi Jap
Javi Jap 2017-6-3
You are right, it was a byte order issue. After swapping the bytes it works as expected. Thanks!

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by