简体   繁体   English

从 python 中的文件一次读取一个字节

[英]Reading one byte at once from file in python

I have to create a state array (4x4 matrix of 128bit in total, having each element of one byte) for implementing AES in python, how can I read one byte at a time from an input text file.我必须创建一个 state 数组(总共 128 位的 4x4 矩阵,每个元素为一个字节)以在 python 中实现 AES,如何从输入文本文件中一次读取一个字节。

I'll assume you are using NumPy since you mention 4x4 matrix.我假设您使用的是 NumPy,因为您提到了 4x4 矩阵。

Suppose we have text.txt with " this is a TEST ø´®†˙∆\n " as its contents.假设我们有text.txt ,其内容为“ this is a TEST ø´®†˙∆\n ”。 We can use the void data type to work with raw data.我们可以使用 void 数据类型来处理原始数据。

>>> arr = np.fromfile('text.txt', dtype='|V1')
>>> arr
array([b'\x74', b'\x68', b'\x69', b'\x73', b'\x20', b'\x69', b'\x73',
       b'\x20', b'\x61', b'\x20', b'\x54', b'\x45', b'\x53', b'\x54',
       b'\x20', b'\xC3', b'\xB8', b'\xC2', b'\xB4', b'\xC2', b'\xAE',
       b'\xE2', b'\x80', b'\xA0', b'\xCB', b'\x99', b'\xE2', b'\x88',
       b'\x86', b'\x0A'], dtype='|V1')

This results in the same data as, although ASCII is displayed as characters.这会产生与 ASCII 相同的数据,尽管 ASCII 显示为字符。

>>> with open('text.txt', 'rb') as fp:
...     byte = fp.read()
>>> byte
b'this is a TEST \xc3\xb8\xc2\xb4\xc2\xae\xe2\x80\xa0\xcb\x99\xe2\x88\x86\n'

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

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