Clear Filters
Clear Filters

Pythons unpack_From in Matlab

10 views (last 30 days)
Greetings!
I am receiving some data over UDP in form of array of integers. For example y= [ 67 36 73 43] this is the data received. The actual sensor value is 161.0.
I am not able to convert this received data to 161.0.
However when I have used Python's script using unpack_fom I was able to decode to correct value of 161.0
Python code : >>> pack('!f',161) 'C!\x00\x00' >>> unpack_from('!f','C!\x00\x00') (161.0,)
Let me know if anyone has better solution to decode value [67 36 73 43] to 161.0 float value

Accepted Answer

Robert Snoeberger
Robert Snoeberger on 2 Mar 2017
Edited: Robert Snoeberger on 3 Mar 2017
The function typecast [1] might do what you want. I'm going to give an example of how to use it but I need to make a few assumptions.
  1. I'm assuming that the integers you received are uint8.
  2. Since you have only 4 integers, the value 161.0 must be a single precision floating point number. I think that this is consistent with your use of 'f' in the pack and unpack_from functions.
Example:
To learn a little about typecast, I will start by converting the value 161.0 into an array of integers.
>> y = typecast(single(161.0), 'uint8')
y =
1×4 uint8 row vector
0 0 33 67
>>
Note that the value 67 is at the end instead of the beginning of the array. I can use the function swapbytes [2] to swap the byte ordering of the value 161.0 before the type cast. I think this byte swap is consistent with your use of '!' in the pack and unpack_from functions.
>> v = swapbytes(single(161.0));
>> sy = typecast(v, 'uint8')
sy =
1×4 uint8 row vector
67 33 0 0
>>
Now, to covert the data you received to a value ~161, just do these operations in reverse.
>> y = uint8([67 36 73 43]);
>> v = typecast(y, 'single');
>> swapbytes(v)
ans =
single
164.2858
>>
Edit: Fixed a typo in the display of sy. Original display was incorrect.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!