MATLAB and Python solutions are equivalent.
The only difference I noticed is that MATLAB result is of class double, and in Python the ndarray elements are of type uint8.
(The type differences are probably not relevant).
There are small issues with the sample code you have posted that makes it non-executable:
- The MATLAB code should be:
dec2hex(startAddress, 8) instead of dec2hex(address, 8).
- The Python code should be:
np.frombuffer(address, instead of np.frombuffer(addressMsg,.
You may get the same result using simpler code:
In MATLAB you can use typecast:
address = double(typecast(uint32(startAddress), 'uint8')');
Sample code for testing:
startAddress = hex2dec('12345678');
address = hex2dec(flipud((reshape(dec2hex(startAddress, 8), 2, 4))'));
address2 = double(typecast(uint32(startAddress), 'uint8')');
In Python you can use struct.pack:
address = np.frombuffer(struct.pack("<I", startAddress), np.uint8).reshape(4,1)
Sample code for testing:
startAddress = int('12345678', 16)
address = startAddress.to_bytes(8, 'little')
address = np.frombuffer(address, dtype=np.uint8)
address = address[0:4].reshape(4,1)
# Convert startAddress array of 4 uint8 elements (apply little endian format).
address2 = np.frombuffer(struct.pack("<I", startAddress), np.uint8).reshape(4,1)
MATLAB execution result:
address =
120
86
52
18
address2 =
120
86
52
18
Python execution result:
address
array([[120],
[ 86],
[ 52],
[ 18]], dtype=uint8)
address2
array([[120],
[ 86],
[ 52],
[ 18]], dtype=uint8)
address = 0 0 208 0