1

I have sent a number from Matlab via UDP using the commands below:

u=udp('192.168.137.239',5004) ;create UDP object
u.OutputBufferSize = 1000;
fopen(u)
fwrite(u,200,'int' ) ; write number 200

but when I receive this number on the Raspberry in python via UDP, it is not displayed correctly (it display 3355443200L), I use unpack to convert as in the following code:

import sys, struct
from socket import*
import numpy
import numpy as np
import pickle

SIZE = 65535

hostName = gethostbyname('0.0.0.0')

mySocket = socket(AF_INET, SOCK_DGRAM)
mySocket.bind((hostName,5004))

repeat = True


while repeat:
    (data, addr)=mySocket.recvfrom(SIZE)
    data1 = struct.unpack('I', data)
    print " received meassage:",data1

Please tell me how to convert binary from Matlab into integer in python.

Dmitry Grigoryev
  • 28,277
  • 6
  • 54
  • 147
Xúc Cảm
  • 51
  • 1
  • 6

1 Answers1

2

3355443200L is in fact C8000000 in hex format, which is the number 200 padded by three extra zero bytes. This happens because UDP data is transmitted in Network byte order, while fwrite writes data in the computer's natural order (little endian on Intel computers).

You will need to swap the bytes manually before sending them from Matlab, using swapbytes:

fwrite(u,swapbytes(int32(200)),'int'); Write integer number 200

Another option is to change the transmission byteorder using u.ByteOrder = 'littleEndian', but I don't have Matlab to test how that works.

Dmitry Grigoryev
  • 28,277
  • 6
  • 54
  • 147