[英]How to read/write binary 16-bit data in Python 2.x?
I have to read and write binary data, where each element of data: 我必须读取和写入二进制数据,其中每个数据元素:
Is it possible without using any external module? 是否可以不使用任何外部模块? If yes,
如是,
I think you are best off using the array
module. 我认为你最好使用
array
模块。 It stores data in system byte order by default, but you can use array.byteswap()
to convert between byte orders, and you can use sys.byteorder
to query the system byte order. 它默认以系统字节顺序存储数据,但您可以使用
array.byteswap()
在字节顺序之间进行转换,您可以使用sys.byteorder
查询系统字节顺序。 Example: 例:
# Create an array of 16-bit signed integers
a = array.array("h", range(10))
# Write to file in big endian order
if sys.byteorder == "little":
a.byteswap()
with open("data", "wb") as f:
a.tofile(f)
# Read from file again
b = array.array("h")
with open("data", "rb") as f:
b.fromfile(f, 10)
if sys.byteorder == "little":
b.byteswap()
from array import array
# Edit:
from sys import byteorder as system_endian # thanks, Sven!
# Sigh...
from os import stat
def read_file(filename, endian):
count = stat(filename).st_size / 2
with file(filename, 'rb') as f:
result = array('h')
result.fromfile(f, count)
if endian != system_endian: result.byteswap()
return result
Consider using 考虑使用
struct.unpack(byteorder + str(len(rawbytes) // 2) + "h", rawbytes)
where byteorder
is '<'
or '>'
as desired, and similarly for packing. 其中
byteorder
是'<'
或'>'
,并且类似于打包。 Note: I'm not claiming that this is faster than the array
way, but I do note that the array
way sometimes needs an additional byteswap
step. 注意:我没有声称这比
array
方式更快,但我注意到array
方式有时需要一个额外的byteswap
步骤。
I found this useful for reading/writing the data from a binary file into a numpy array: 我发现这对于从二进制文件读取/写入数据到numpy数组非常有用:
import numpy as np
sys.argv[1] = endian # Pass endian as an argument to the program
if endian == 'big':
precTypecode = '>'
elif endian == 'little':
precTypecode = '<'
# Below: 'i' is for signed integer and '2' is for size of bytes.
# Alternatively you can make this an if else statement to choose precision
precTypecode += 'i2'
im = np.fromfile(inputFilename, dtype = precTypecode) # im is now a numpy array
# Perform any operations you desire on 'im', for example switching byteorder
im.byteswap(True)
# Then write to binary file (note: there are some limitations, so refer doc)
im.tofile(outputFilename)
Hope this helps. 希望这可以帮助。
As asked, without any external modules: 如所要求的,没有任何外部模块:
with open("path/file.bin", "rb") as file:
byte_content = file.read()
list_16bits = [byte_content[i + 1] << 8 | byte_content[i] for i in range(0, len(byte_content), 2)]
In the comprehension list, we read each two bytes. 在理解列表中,我们读取每两个字节。 Then, with bitwise operation we concatenate those 2 bytes.
然后,通过按位运算,我们连接这2个字节。 It depends of the endianess for where to write
i+1
and i
这取决于在哪里写
i+1
和i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.