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. H
great example here:
>> dataL = typecast(uint8([189, 33, 136, 147]), 'uint32')
dataL =
2475172285
>> dataF = double(dataL)
dataF =
2.4752e+09
big to little, try swapbytes
>> dataLbig = swapbytes(dataL)
dataLbig =
3173091475
>> dataFbig = double(dataLbig)
dataFbig =
3.1731e+09
Is this what you were expecting?
I'll leave this here in case it's useful for anyone. As @MarkMikofski showed, using typecast
and swapbytes
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:
function x = Bit32toDouble(y)
n = numel(y);
if n >= 65536
x = double(swapbytes(typecast(uint8(y(:)),'uint32'))).';
elseif n > 4
x = sum(bsxfun(@times,[16777216;65536;256;1],reshape(y(:),4,n/4)));
else
x = sum([16777216;65536;256;1].*y(:));
end
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.