python 确定字节顺序的最 Pythonic 方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1346034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:01:12  来源:igfitidea点击:

What's the most Pythonic way of determining endianness?

pythonendianness

提问by Major Major

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:

我试图找到确定运行我的代码的机器是大端还是小端的最佳方法。我有一个有效的解决方案(虽然我没有在大端机器上测试过它)但它似乎有点笨拙:

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?

这只是将“本机”两字节包与小端包进行比较。有没有更漂亮的方法?

回答by Scott Griffiths

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.

当然,根据您的机器,它可能会返回'big'。你的方法当然也应该有效。