什么字节顺序不Python中使用写入到文件? [英] What endianness does Python use to write into files?

查看:153
本文介绍了什么字节顺序不Python中使用写入到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用带WB标志,并使用Python的或大或豆蔻端,或sys.byteorder值file.write()?我怎么能肯定的是,字节顺序不是随机的,我问,因为我在同一个文件和我使用struct.pack(二进制数据混合的ASCII和二进制数据),并强制其小端,但我不知道什么发生在ASCII数据!

When using file.write() with 'wb' flag does Python use big or litte endian, or sys.byteorder value ? how can i be sure that the endianness is not random, I am asking because I am mixing ASCII and binary data in the same file and for the binary data i use struct.pack() and force it to little endian, but I am not sure what happen to the ASCII data !

编辑1:自downvote,我会更多地解释我的问题。

Edit 1: since the downvote, I'll explain more my question !

我写ASCII码和二进制数据的文件,在x86的PC,该文件将通过网络传输到另一台计算机女巫被送到不是x86上,PowerPC的,女巫是大端,我怎么能肯定当使用PowerPC分析的数据将是相同的?

I am writing a file with ASCII and binary data, in a x86 PC, the file will be sent over the network to another computer witch is not x86, a PowerPC, witch is on Big-endian, how can I be sure that the data will be the same when parsed with the PowerPC ?

编辑2:依然使用Python 2.7

Edit 2: still using Python 2.7

推荐答案

有关多字节数据,它遵循机器的默认架构。如果你需要它的跨平台工作,那么你会想强迫。

For multibyte data, It follows the architecture of the machine by default. If you need it to work cross-platform, then you'll want to force it.

ASCII和UTF-8都设有codeD,因为每个字符一个字节,因此它受字节顺序?号

ASCII and UTF-8 are encoded as a single byte per character, so is it affected by the byte ordering? No.

下面是如何收拾小< 或大> 字节序:

Here is how to pack little < or big > endian:

import struct

struct.pack('<L', 1234)
'\xd2\x04\x00\x00'

struct.pack('>L', 1234)
'\x00\x00\x04\xd2'

您也可以连接code字符串作为大或小尾数这样,如果您使用的是UTF-16,作为一个例子:

You can also encode strings as big or little endian this way if you are using UTF-16, as an example:

s.encode('utf-16LE')
s.encode('utf-16BE')

UTF-8,ASCII没有字节顺序,因为它是每个字符1个字节。

UTF-8, ASCII do not have endianness since it is 1 byte per character.

这篇关于什么字节顺序不Python中使用写入到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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