如何在Python中将长整数写为二进制? [英] How do I write a long integer as binary in Python?

查看:164
本文介绍了如何在Python中将长整数写为二进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,长整数具有无限的精度.我想将16字节(128位)整数写入文件.标准库中的struct仅支持最多8个字节的整数. array具有相同的限制.有没有一种方法可以做到,而无需掩盖和移动每个整数?

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 up to 8 byte integers. array has the same limitation. Is there a way to do this without masking and shifting each integer?

这里有一些说明:我正在写一个将从非Python程序中读取的文件,所以泡菜不见了.全部使用了128位.

Some clarification here: I'm writing to a file that's going to be read in from non-Python programs, so pickle is out. All 128 bits are used.

推荐答案

两种可能的解决方案:

  1. 只需 pickle 您的长整数.这将以一种特殊的格式写入整数,如果需要的话,可以再次读取该整数.

  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.

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.

问题在于bigints的内部表示不直接包含您要求的二进制数据.

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

这篇关于如何在Python中将长整数写为二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆