【问题标题】:C++ / Python Equivalent of Matlab's num2hexC++/Python 等价于 Matlab 的 num2hex
【发布时间】:2014-09-07 13:38:10
【问题描述】:

C++ 或 Python 中是否有等效于 MATLAB 的num2hex 函数的函数?

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

【问题讨论】:

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


    【解决方案1】:

    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'
    

    【讨论】:

      【解决方案2】:
      1. 很遗憾,这不适用于负数(32 位浮点数、64 位浮点数),因为在解包操作之后包含减号。通过将“l”更改为大写“L”并将“q”更改为大写“Q”,可以使用无符号表示。
      2. 此外,十六进制数字以大端格式显示。为了让 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])
        

      【讨论】:

        猜你喜欢
        • 2021-08-07
        • 2012-10-18
        • 2022-11-02
        • 1970-01-01
        • 1970-01-01
        • 2014-10-17
        • 2021-11-25
        • 2016-11-02
        • 1970-01-01
        相关资源
        最近更新 更多