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

后端 未结 9 1217
梦谈多话
梦谈多话 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:43

    Based on @DSM's answer, and to support negative integers and varying byte sizes, I've created the following improved snippet:

    def to_bytes(num, size):
            x = num if num >= 0 else 256**size + num
            h = hex(x)[2:].rstrip("L")
            return binascii.unhexlify("0"*((2*size)-len(h))+h)
    

    This will properly handle negative integers and let the user set the number of bytes

提交回复
热议问题