Convert Hex to single precision

和自甴很熟 提交于 2019-12-12 11:33:10

问题


I'm struggling with converting a 32-bit hex expression into a single precision number in Matlab.

The num2hex function works fine for both. For example,

>> b = 0.4

b =

   0.400000000000000

>> class(b)

ans =

double

>> num2hex(b)

ans =

3fd999999999999a

>> num2hex(single(b))

ans =

3ecccccd

However, this does not work the other way around. The hex2num function only converts hexadecimal expression into doubles. So,

>> b = 0.4

b =

   0.400000000000000

>> num2hex(single(b))

ans =

3ecccccd

>> hex2num(ans)

ans =

    3.433227902860381e-006

Matlab simply pads zeros to make it a 64-bit hex. Is there a way to perform this conversion?


回答1:


It doesn't seem to be possible with the built-in hex2num, but fortunately you can get a single precision version of hex2num (hexsingle2num) here: http://www.mathworks.com/matlabcentral/fileexchange/6927-hexsingle2num




回答2:


There's a way I found to do this usign built in functions in MATLAB

%#Let's convert 0x40100000 to Single Precision Float (should equal 2.25)

tempHex = '40100000';

tempVal = uint32(hex2dec(tempHex));

tempFloat = typecast(tempVal,'single')
%#result is 2.25


来源:https://stackoverflow.com/questions/7207413/convert-hex-to-single-precision

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