how to convert negative integer value to hex in python

前端 未结 3 574
我寻月下人不归
我寻月下人不归 2020-12-08 10:17

I use python 2.6

>>> hex(-199703103)
\'-0xbe73a3f\'

>>> hex(199703103)
\'0xbe73a3f\'

Positive and negative value are the

3条回答
  •  半阙折子戏
    2020-12-08 10:40

    Because Python integers are arbitrarily large, you have to mask the values to limit conversion to the number of bits you want for your 2s complement representation.

    >>> hex(-199703103 & (2**32-1)) # 32-bit
    '0xf418c5c1L'
    >>> hex(-199703103 & (2**64-1)) # 64-bit
    '0xfffffffff418c5c1L'
    

    Python displays the simple case of hex(-199703103) as a negative hex value (-0xbe73a3f) because the 2s complement representation would have an infinite number of Fs in front of it for an arbitrary precision number. The mask value (2**32-1 == 0xFFFFFFFF) limits this:

    FFF...FFFFFFFFFFFFFFFFFFFFFFFFF418c5c1
    &                             FFFFFFFF
    --------------------------------------
                                  F418c5c1
    

提交回复
热议问题