How do I write a long integer as binary in Python?

后端 未结 9 1337
梦谈多话
梦谈多话 2021-01-12 06:20

In Python, long integers have unlimited precision. I would like to write a 16 byte (128 bit) integer to a file. struct from the standard library supports only u

9条回答
  •  不要未来只要你来
    2021-01-12 06:39

    This may not avoid the "mask and shift each integer" requirement. I'm not sure that avoiding mask and shift means in the context of Python long values.

    The bytes are these:

    def bytes( long_int ):
        bytes = []
        while long_int != 0:
            b = long_int%256
            bytes.insert( 0, b )
            long_int //= 256
        return bytes
    

    You can then pack this list of bytes using struct.pack( '16b', bytes )

提交回复
热议问题