解码ASCII码时,是否应故意省略奇偶校验位?

2024-04-23 09:58:01 发布

您现在位置:Python中文网/ 问答频道 /正文

根据维基百科,ASCII是一种7位编码。由于每个地址(当时和现在)存储8位,因此多余的第8位可以用作奇偶校验位

The committee voted to use a seven-bit code to minimize costs associated with data transmission. Since perforated tape at the time could record eight bits in one position, it also allowed for a parity bit for error checking if desired.[3]:217, 236 §5 Eight-bit machines (with octets as the native data type) that did not use parity checking typically set the eighth bit to 0.

似乎没有什么规定存储ASCII字符的字节中的第8位必须为0。因此,在解码ASCII字符时,我们是否必须考虑第8位可能被设置为1的可能性?Python似乎没有考虑到这一点——应该吗?或者我们是否保证奇偶校验位始终为0(根据某些官方标准)

示例

如果奇偶校验位为0(默认值),则Python可以解码字符(“@”):

int('0b01000000', 2).to_bytes(1, byteorder='little').decode("ascii")
# Outputs: '@'

但如果奇偶校验位设置为1,则byte.decode失败:

int('0b11000000', 2).to_bytes(1, byteorder='little').decode("ascii")
""" Outputs:
Traceback (most recent call last):
  File "<pyshell#61>", line 1, in <module>
    int('0b11000000', 2).to_bytes(1, byteorder='little').decode("ascii")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc0 in position 0: ordinal not in range(128)
"""

但第8位的值应该无关紧要,因为ASCII仅使用7位。注意:我不是问如何使byte.decode使用非零奇偶校验位,而是问解码器是否应该显式忽略它


Tags: thetoinbytesuseasciibitbyte
1条回答
网友
1楼 · 发布于 2024-04-23 09:58:01

奇偶校验位可以设置的事实只是一个观察,而不是一个普遍遵循的协议。也就是说,我知道没有编程语言在解码ASCII码时真正关心奇偶校验。如果设置了最高位,则该数字仅被视为>=128,这超出了已知ASCII字符的范围

相关问题 更多 >