简体   繁体   English

如何在MATLAB中将定点(Q格式)数字转换为浮点数

[英]How to convert fixed point (Q format) number to floating point in MATLAB

Why int16 doesn't retrieve the sign from an hex string? 为什么int16不从十六进制字符串中检索符号?

MATLAB: MATLAB:

>> single(int16(hex2dec('ffff')))
ans =

       32767

ie

>> int16(hex2dec('ffff')) == int16(hex2dec('8fff'))

ans =

     1

To put it in its general context, I want to rewrite the following numpy Python snippet code in MATLAB: 为了将其放在一般上下文中,我想在MATLAB中重写以下numpy Python代码段代码:

>>> import numpy as np 
>>> i='ffff'
>>> q='3fff'
>>> i_float = np.int16(int(i,16))
>>> i_float = i_float * 2 ** -15
>>> i_float
-3.0517578125e-05
>>> q_float = np.int16(int(q,16))
>>> q_float = q_float * 2 ** -15
>>> q_float
0.499969482421875

Here's what I've got. 这就是我所拥有的。 (Yes, it seems to be more convoluted than it should be.) (是的,它似乎比应该的要复杂得多。)

i_hex = 'ffff'
q_hex = '3fff'

i_int16 = typecast(uint16(hex2dec(i_hex)),'int16')
i_float = single(i_int16) * 2 ^ -15

q_int16 = typecast(uint16(hex2dec(q_hex)),'int16')
q_float = single(q_int16) * 2 ^ -15

Output: 输出:

i_hex = ffff
q_hex = 3fff
i_int16 = -1
i_float =   -3.05175781250000e-05
q_int16 = 16383
q_float =  0.499969482421875

hex2dec converts hex to a double, so I cast it to a uint16 so as to preserve the sign bit (which hex2dec refuses to do). hex2dechex2dec转换为double,因此我将其转换为uint16 ,以便保留符号位( hex2dec拒绝这样做)。 Then I typecast the result to a signed int16 . 然后,将结果typecast为带符号的int16 This just takes the bits of the uint16 and interprets them as an int16 . 这只是获取uint16的位并将其解释为int16 Then cast it to a single and bitshift. 然后将其强制转换为single移位。

Note: I used format long to see as many decimal places as I could. 注意:我使用format long来查看尽可能多的小数位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM