I have the following bytes stored in a vector:
data = [189 33 136 147]
These 4 bytes represent a single float in Big-endian order. How can I get this number in MATLAB?
I will need to concatenate and convert. I tried:
x = typecast(str2num(sprintf('%d%d%d%d',data(1),data(2),data(3),data(4))), 'single')
To no avail (I got x = []
).
I'll leave this here in case it's useful for anyone. As @MarkMikofski showed, using
typecast
andswapbytes
is the standard method for this. However, if you your data is already floating-point, these functions can be inefficient in some cases. I use the following utility function in my video-encoding/decoding tools:There are separate cases depending on the number of bytes passed in. Only when a large amount of data is processed at once is the
typecast
/swapbytes
most efficient. If the function is called repeatedly with smaller inputs, as is common in my application, the other cases are much faster because they do every thing in Matlab's native floating-point.great example here:
big to little, try
swapbytes
Is this what you were expecting?