【发布时间】:2014-09-07 13:38:10
【问题描述】:
C++ 或 Python 中是否有等效于 MATLAB 的num2hex 函数的函数?
Python 的 float.hex 和 int.hex 函数给出的结果与 MATLAB 的 num2hex 函数不同。
【问题讨论】:
标签: python c++ matlab hex floating-point-conversion
C++ 或 Python 中是否有等效于 MATLAB 的num2hex 函数的函数?
Python 的 float.hex 和 int.hex 函数给出的结果与 MATLAB 的 num2hex 函数不同。
【问题讨论】:
标签: python c++ matlab hex floating-point-conversion
% single
>> num2hex(single(1))
ans =
3f800000
% double
>> num2hex(1)
ans =
3ff0000000000000
>>> 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'
【讨论】:
此外,十六进制数字以大端格式显示。为了让 little-endian 格式使用 '
# 32-bit float
>>> hex(struct.unpack('<L', struct.pack('<f', x))[0])
# 64-bit float
>>> hex(struct.unpack('<Q', struct.pack('<d', x))[0])
【讨论】: