如何读取具有字节格式的 16 位有符号整数的整个二进制文件,并将文件中的内容打印为 python 中的整数数组?
如何将包含正整数和负整数的数组写入二进制文件。每个整数必须以两个字节写入。以及如何通过将字节转换回整数来读取该二进制文件。
示例: arr=[-32767,-32789,-1200,0,6789,34589] -> 输入数组 每个值必须转换为两个字节并写入二进制文件“binaryfile.bin”,
现在的要求是读取整个文件(“binaryfile.bin”)并将这些字节转换为值并将其打印为数组outputarray=[ -32767,-32789,-1200,0,6789,34589]
How to write an array containing both positive and negative integers into the binary file. Each integers must be written in two bytes. And how to read that binary file by converting the bytes back into the integers.
example: arr=[-32767,-32789,-1200,0,6789,34589] ->input array
each value must be converted into two bytes and are written into the binary file "binaryfile.bin"
now the requirement is to read entire file ( "binaryfile.bin") and convert those bytes into values and print it as an array outputarray=[-32767,-32789,-1200,0,6789,34589]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Numpy 可以帮助您:
https://numpy.org /doc/stable/reference/ generated/numpy.ndarray.tobytes.html
https://numpy.org/doc/stable/reference/ generated/numpy.frombuffer.html
请参阅以下示例:
请注意,数字
34589
是大于 2^15,因此无法存储为两个字节的有符号整数,它将转换为-30947
(整数溢出)。您可以存储第二个数组,指示哪个数字是有符号整数或无符号整数,但这可能会比仅存储整数 32 更复杂。注意:
作为与其他人共享二进制文件时的一个小警告,请确保您同意字节顺序,请参阅 https://en.wikipedia.org/wiki/Endianness
Numpy can help you with that:
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.tobytes.html
https://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html
See the following example:
Note that the number
34589
is larger than 2^15 and therefore cannot be stored as signed integer of two bytes it will be converted to-30947
(integer overflow). You could store a second array indicating which number is a signed or an unsigned integer, but this could become more complicated than jsut storing integer 32.Note:
As a small warning when sharing binary files with other people, please also be sure that you agree on the byte order, see https://en.wikipedia.org/wiki/Endianness