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

后端 未结 9 1320
梦谈多话
梦谈多话 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 07:03

    The PyPi bitarray module in combination with the builtin bin() function seems like a good combination for a solution that is simple and flexible.

    bytes = bitarray(bin(my_long)[2:]).tobytes()
    

    The endianness can be controlled with a few more lines of code. You'll have to evaluate the efficiency.

提交回复
热议问题