将字节字符串列表转换为bytearray(字节流) [英] Convert list of byte strings to bytearray (byte stream)

查看:291
本文介绍了将字节字符串列表转换为bytearray(字节流)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代表字节的十六进制字符串列表,形式为"FF".我想将整个列表转换为字节流,以便可以通过套接字发送它(Python 3).看起来bytearray类型可以工作,但是我找不到任何将列表直接转换为bytearray的方法.

I have a list of hex strings representing bytes, of the form "FF". I want to convert the whole list to a byte stream so I can send it over a socket (Python 3). It looks like the bytearray type would work, but I can't find any way to directly convert the list to a bytearray.

我可以循环手动执行此操作,但是必须找到一种更好的Python方式来完成此操作.

I can do it manually in a loop, but figure there must be a better Python way to do this.

推荐答案

hexstrings = ["DE", "AD", "BE", "EF"]   # big-endian 0xDEADBEEF

bytes = bytearray(int(x, 16) for x in hexstrings)
bytes = bytearray.fromhex("".join(hexstrings))     # Python 2.6 may need u""

如果您有很多'em,可能值得看看其中哪一个最快.

If you've got a lot of 'em, it might be worthwhile to see which of those is fastest.

这篇关于将字节字符串列表转换为bytearray(字节流)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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