C ++ / Python相当于Matlab的num2hex

时间:2014-07-16 21:04:13

标签: python c++ matlab hex floating-point-conversion

C ++或Python中的函数是否等同于MATLAB' num2hex函数?

Python的float.hexint.hex函数与MATLAB的num2hex函数的结果不同。

3 个答案:

答案 0 :(得分:2)

MATLAB

% single
>> num2hex(single(1))
ans =
3f800000

% double
>> num2hex(1)
ans =
3ff0000000000000

的Python

>>> x = 1.0

# 32-bit float
>>> hex(struct.unpack('!l', struct.pack('!f',x))[0])
'0x3f800000'

# 64-bit float
>>> hex(struct.unpack('!q', struct.pack('!d',x))[0])
'0x3ff0000000000000L'

答案 1 :(得分:1)

  1. 不幸的是,这对于负数(32位浮点数,64位浮点数)不起作用,因为在拆包操作后会包含减号。通过将“ l”更改为大写字母“ L”,将“ q”更改为大写字母“ Q”,将使用无符号表示。
  2. 此外,十六进制数字以big-endian格式显示。为了具有小尾数格式,请使用'<'代替'!'。

    sed 's/.\{20\}\(.\).*/\1/;q'
    
    grep -f index_file sequence_file   # also tried with grep 
    

答案 2 :(得分:0)

大多数MATLAB函数采用数据类型为double的数字输入参数。最佳实践是确保作为输入参数传递给MATLAB函数的数字为Python数据类型float,而不是Python数据类型int。如果您执行以下操作,则可以确保Python变量是浮点数:

相关问题