Is there a function in C++ or Python that is equivalent to MATLAB's num2hex function?
Python's float.hex
and int.hex
functions do not give the same result as MATLAB's num2hex
function.
Is there a function in C++ or Python that is equivalent to MATLAB's num2hex function?
Python's float.hex
and int.hex
functions do not give the same result as MATLAB's num2hex
function.
% 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'
Furthermore, the hexadecimal numbers are displayed in big-endian format. In order to have little-endian format use '<' instead of '!'.
# 32-bit float
>>> hex(struct.unpack('<L', struct.pack('<f', x))[0])
# 64-bit float
>>> hex(struct.unpack('<Q', struct.pack('<d', x))[0])