MATLAB convert big-endian order bytes into floating point values

ぃ、小莉子 提交于 2019-11-30 19:24:42

问题


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


回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/20535028/matlab-convert-big-endian-order-bytes-into-floating-point-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!