我们为什么要在这里使用endianness?

2024-04-25 23:35:54 发布

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

我正在读一个source-code,它下载zip文件并将数据读入numpy数组。代码假设可以在macos和linux上运行,下面是我看到的片段:

def _read32(bytestream):
    dt = numpy.dtype(numpy.uint32).newbyteorder('>')
    return numpy.frombuffer(bytestream.read(4), dtype=dt)

此函数用于以下上下文:

^{pr2}$

不难看出这里发生了什么,但我对newbyteorder('>')的目的感到困惑。我读了documentation,知道endianness是什么意思,但不明白为什么开发人员要添加newbyteorder(在我看来,这不是真正需要的)。在


Tags: 文件数据代码numpysourcelinuxdefdt
2条回答

它只是一种确保从结果数组中以正确顺序解释字节的方法,而不管系统的本机字节顺序如何。在

默认情况下,内置的NumPy integer数据类型将使用系统本机的字节顺序。例如,我的系统是little-endian,所以简单地使用dtype numpy.dtype(numpy.uint32)将意味着从一个以big-endian顺序的字节从缓冲区读入数组的值将不能正确解释。在

如果np.frombuffer要接收已知按特定字节顺序排列的字节,最佳做法是使用newbyteorder修改数据类型。这在documents for ^{}中提到:

Notes

If the buffer has data that is not in machine byte-order, this should be specified as part of the data-type, e.g.:

>>> dt = np.dtype(int)
>>> dt = dt.newbyteorder('>')
>>> np.frombuffer(buf, dtype=dt)

The data of the resulting array will not be byteswapped, but will be interpreted correctly.

这是因为下载的数据是big-endian格式的,如source page:http://yann.lecun.com/exdb/mnist/

All the integers in the files are stored in the MSB first (high endian) format used by most non-Intel processors. Users of Intel processors and other low-endian machines must flip the bytes of the header.

相关问题 更多 >