Search code examples
pythonc++matlabhexfloating-point-conversion

C++ / Python Equivalent of Matlab's num2hex


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.


Solution

  • 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'