MATLAB convert big-endian order bytes into floatin

2019-02-15 07:27发布

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 = []).

2条回答
你好瞎i
2楼-- · 2019-02-15 07:46

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.

查看更多
Anthone
3楼-- · 2019-02-15 07:47

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?

查看更多
登录 后发表回答