2

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.

Amro
  • 123,847
  • 25
  • 243
  • 454
Armin Meisterhirn
  • 801
  • 1
  • 13
  • 26

2 Answers2

3

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'
Amro
  • 123,847
  • 25
  • 243
  • 454
2
  1. Unfortunately, this does not work for negative numbers (32-bit float, 64-bit float) since the minus symbol is included after the unpacking operation. By changing 'l' to uppercase 'L' and 'q' to uppercase 'Q' unsigned representations are used instead.
  2. 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])
    
DaniL
  • 21
  • 2