Converting a value into 4 byte hex in python

后端 未结 1 1858
我寻月下人不归
我寻月下人不归 2021-01-28 11:09

I want to convert any value (that can be negative or positive) into hex. My current method does this.

The read value in this example is 4003.

workingline         


        
相关标签:
1条回答
  • 2021-01-28 11:44

    You want the struct module:

    >>> struct.pack("<I", 4003).encode('hex')
    'a30f0000'
    

    For -2, you'll need to do some other work:

    >>> struct.pack("<I", -2 + 2**32).encode('hex')
    'feffffff'
    

    A way to do it for any value is:

    struct.pack("<I", (value + 2**32) % 2**32).encode('hex')
    
    0 讨论(0)
提交回复
热议问题