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

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

    Two possible solutions:

    1. Just pickle your long integer. This will write the integer in a special format which allows it to be read again, if this is all you want.

    2. Use the second code snippet in this answer to convert the long int to a big endian string (which can be easily changed to little endian if you prefer), and write this string to your file.

    The problem is that the internal representation of bigints does not directly include the binary data you ask for.

提交回复
热议问题