简体   繁体   English

为什么Python中的bytearray函数将一个字节变成两个字节?

[英]Why does bytearray function in Python turn one byte into two bytes?

I'm attempting to create a data encoder in Python.我正在尝试在 Python 中创建一个数据编码器。 I'm using my own unique underlying symmetric algorithm to encode a single 8-bit byte to another 8-bit byte and then decode it using the same algorithm.我使用自己独特的底层对称算法将单个 8 位字节编码为另一个 8 位字节,然后使用相同的算法对其进行解码。

I'm using Python's bytearray function to turn strings into bytes.我正在使用 Python 的 bytearray 函数将字符串转换为字节。 However I'm running into this issue: The hexadecimal xAB can be represented in binary as 1010 1011 .但是我遇到了这个问题:十六进制 xAB 可以用二进制表示为1010 1011 Yet when I use byte array on the string representation ("\\xAB") I get:然而,当我在字符串表示形式("\\xAB")上使用字节数组时,我得到:

>>> byte = bytearray("\xAB", "utf-8")
>>> print(byte)
bytearray(b'\xc2\xab')

Clearly the string is represented in the single byte of \\xAB , but why is the other byte \\xC2 being prepended to the byte array?显然,字符串以\\xAB的单个字节表示,但为什么另一个字节\\xC2被添加到字节数组中? I'm using UTF-8 to encode the data since that is Python's default, but should I be using a different encoding?我使用 UTF-8 对数据进行编码,因为这是 Python 的默认设置,但我应该使用不同的编码吗? How can I get the bytearray to contain only the 8 bit byte needed to represent xAB?如何让 bytearray 只包含表示 xAB 所需的 8 位字节?

"\\xAB" is a string consisting of the single Unicode character U+00AB. "\\xAB"是由单个 Unicode 字符 U+00AB 组成的字符串。 You then convert it to a byte array, using the UTF-8 encoding.然后使用 UTF-8 编码将其转换为字节数组。 But in UTF-8, the character U+00AB is encoded as two bytes — C2, AB.但在 UTF-8 中,字符 U+00AB 被编码为两个字节——C2、AB。 That the second byte happens to be the same as the input byte in this case is a coincidence;在这种情况下,第二个字节恰好与输入字节相同是巧合; it will not always be the case.情况并非总是如此。

If you want to deal with byte arrays, you are probably better off leaving strings out of it, as strings always bring encoding headaches with them.如果您想处理字节数组,最好将字符串排除在外,因为字符串总是会带来编码问题。

The erroneous byte seem to be coming from the escape character in your string.错误的字节似乎来自字符串中的转义字符。 When encoding from string to byte, I recommend using python's new notation:当从字符串编码到字节时,我建议使用 python 的新符号:

>> byte = bytearray(b"xAB")
>> print(byte)
bytearray(b'xAB')

Also, to debug your code, consider reversing the encoding to see what python is seeing: (clearly not the correct value)另外,要调试您的代码,请考虑反转编码以查看 python 看到的内容:(显然不是正确的值)

>>> byte = bytearray("\xAB", "utf-8")
>>> byte.decode()
'«'

Using the changes provided above, the correct value is returned:使用上面提供的更改,返回正确的值:

>>> byte = bytearray(b'xAB')
>>> byte.decode()
'xAB'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM