How to receive signed integer through socket

3 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 3 Jun 2017
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 Comment
Javi Jap
Javi Jap on 3 Jun 2017
You are right, it was a byte order issue. After swapping the bytes it works as expected. Thanks!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!