I'm trying to find the best way of working out whether the machine my code is running on is big-endian or little-endian. I have a solution that works (although I haven't tested it on a big-endian machine) but it seems a bit clunky:
我正在尝试找出解决我的代码运行的机器是big-endian还是little-endian的最佳方法。我有一个有效的解决方案(虽然我没有在大端机器上测试它)但它看起来有点笨重:
import struct
little_endian = (struct.pack('@h', 1) == struct.pack('<h', 1))
This is just comparing a 'native' two-byte pack to a little-endian pack. Is there a prettier way?
这只是将“本机”双字节包与little-endian包进行比较。有更漂亮的方式吗?
1 个解决方案
#1
75
The answer is in the sys module:
答案在sys模块中:
>>> import sys
>>> sys.byteorder
'little'
Of course depending on your machine it may return 'big'
. Your method should certainly work too though.
当然,根据您的机器,它可能会返回“大”。你的方法当然也应该有效。
#1
75
The answer is in the sys module:
答案在sys模块中:
>>> import sys
>>> sys.byteorder
'little'
Of course depending on your machine it may return 'big'
. Your method should certainly work too though.
当然,根据您的机器,它可能会返回“大”。你的方法当然也应该有效。