Python - 将文件内容转换为二进制数组 [英] Python - Turn a file content into a binary array

查看:76
本文介绍了Python - 将文件内容转换为二进制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件内容:

40 13 123
89 123 2223
4  12  0

我需要将整个 .txt 文件存储为二进制数组,以便稍后将其发送到需要二进制输入的服务器端.

I need to store the whole .txt file as a binary array so that I can send it later to the server side which expects a binary input.

我查看了 Python 的 bytearray 文档.我引用:

I've looked at Python's bytearray documentation. I quote:

返回一个新的字节数组.bytearray 类型是一个可变的整数序列,范围为 0 <= x <;256. 它拥有可变序列的大部分常用方法,在可变序列类型中描述,以及字节类型拥有的大多数方法,参见字节和字节数组方法.

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.


我的数字大于 256,我需要一个 bytearray 数据结构大于 256 的数字.


My numbers are greater than 256, I need a bytearray data structure for numbers that are greater than 256.

推荐答案

你可以使用 array/memoryview 方法

import array
a = array.array('h', [10, 20, 300]) #assume that the input are short signed integers
memv = memoryview(a)
m = memv.cast('b') #cast to bytes
m.tolist()

然后给出 [10, 0, 20, 0, 44, 1]

根据使用情况,也可以这样做:

Depending on the usage, one might also do:

L = array.array('h', [10, 20, 300]).tostring()
list(map(ord, list(L)))

这也给 [10, 0, 20, 0, 44, 1]

这篇关于Python - 将文件内容转换为二进制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆