最近遇到的问题
网络传输socket 需要字节流byte,而UI对话框输入hexstr串,在晚上搜索了一下,做如下记录
- ByteToHex的转换
def ByteToHex( bins ): """ Convert a byte string to it's hex string representation e.g. for output. """ return ''.join( [ "%02X" % x for x in bins ] ).strip() - HexToByte的转换
def HexToByte( hexStr ): """ Convert a string hex byte values into a byte string. The Hex Byte values may or may not be space separated. """ return bytes.fromhex(hexStr) 测试
>>> hexStr2 = "FF FF FF 5F 81 21 07 0C 00 00 FF FF FF FF 5F 81 29 01 0B" >>> hexStr2 'FF FF FF 5F 81 21 07 0C 00 00 FF FF FF FF 5F 81 29 01 0B'
bytes.fromhex(hexStr2) b'\xff\xff\xff_\x81!\x07\x0c\x00\x00\xff\xff\xff\xff_\x81)\x01\x0b'
本文介绍了如何在Python中实现十六进制字符串(Hex)与字节(Byte)之间的相互转换。通过两个函数ByteToHex和HexToByte,可以轻松完成不同格式的数据交换需求。文章包含具体示例代码和测试用例。
383

被折叠的 条评论
为什么被折叠?



