Python中整数的字节顺序 [英] Endianness of integers in Python

查看:514
本文介绍了Python中整数的字节顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个程序,我将一些数据存储在整数中并按位处理。例如,我可能会收到数字48,我会逐位处理。一般来说,整数的字节顺序取决于整数的机器表示,但Python是否做了什么来保证整数总是小端?或者我是否需要像在C中那样检查字节顺序,然后为这两种情况编写单独的代码?

I'm working on a program where I store some data in an integer and process it bitwise. For example, I might receive the number 48, which I will process bit-by-bit. In general the endianness of integers depends on the machine representation of integers, but does Python do anything to guarantee that the ints will always be little-endian? Or do I need to check endianness like I would in C and then write separate code for the two cases?

我问,因为我的代码在Sun机器上运行,虽然现在运行的那个使用英特尔处理器,未来我可能不得不切换到配备Sun处理器的机器,我知道这是大端的。

I ask because my code runs on a Sun machine and, although the one it's running on now uses Intel processors, I might have to switch to a machine with Sun processors in the future, which I know is big-endian.

推荐答案

Python的 int 具有与其运行的处理器相同的字节序。 struct 模块可让您转换字节blob to int(反之亦然,以及其他一些数据类型),无论是native,little-endian还是big-endian方式,具体取决于格式字符串:使用 @ 启动格式,或者使用本机字节顺序没有字节序字符(和本机大小 - 其他一切使用标准大小),'〜'表示原生,'<'表示小端,'>'或'!'表示big-endian。

Python's int has the same endianness as the processor it runs on. The struct module lets you convert byte blobs to ints (and viceversa, and some other data types too) in either native, little-endian, or big-endian ways, depending on the format string you choose: start the format with @ or no endianness character to use native endianness (and native sizes -- everything else uses standard sizes), '~' for native, '<' for little-endian, '>' or '!' for big-endian.

这是逐字节的,而不是逐位的;我不确定你在这种情况下的逐位处理是什么意思,但我认为它可以类似地适应。

This is byte-by-byte, not bit-by-bit; not sure exactly what you mean by bit-by-bit processing in this context, but I assume it can be accomodated similarly.

在简单情况下进行快速批量处理,还要考虑数组模块 - fromstring tostring 方法可以快速操作大量字节,而 byteswap 方法可以获得其他字节序(原生到非原生的,反之亦然),再次迅速和大量的项目(整个数组)。

For fast "bulk" processing in simple cases, consider also the array module -- the fromstring and tostring methods can operate on large number of bytes speedily, and the byteswap method can get you the "other" endianness (native to non-native or vice versa), again rapidly and for a large number of items (the whole array).

这篇关于Python中整数的字节顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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