How to convert integer value to array of four bytes in python

后端 未结 7 1900
太阳男子
太阳男子 2020-12-14 06:54

I need to send a message of bytes in Python and I need to convert an unsigned integer number to a byte array. How do you convert an integer value to an array of four bytes i

相关标签:
7条回答
  • 2020-12-14 07:58

    In case anyone looks at this question sometime later ...
    This statement should be equivalent to the code in the original question:

    >>> tuple( struct.pack("!I", number) )
    ('\x00', '\x00', '\x00', 'd')
    

    And I don't think it matters what the host byte order is.
    If your integers are larger than int32, you can use "!Q" in the call to pack() for int64 (if your system supports Q).
    And list() or even bytearray() will work in place of tuple().

    Note, the result is a sequence of str objects (each holding a single byte), not integers. If you must have a list of integers, you can do this:

    [ ord(c) for c in struct.pack("!I", number) ]
    [0, 0, 0, 100]
    

    ... or this:

    >>> map( ord, tuple( struct.pack("!I", number) ) )
    [0, 0, 0, 100]
    

    But using map() starts making things a bit messy.

    0 讨论(0)
提交回复
热议问题