python str byte hex

来源:互联网 发布:知乎 好听的民谣下载 编辑:程序博客网 时间:2024/06/06 01:49
最近遇到的问题 
    网络传输socket 需要字节流byte,而UI对话框输入hexstr串,在晚上搜索了一下,做如下记录
  1. 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()
  2. 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)
  3. 测试
  4. >>> 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'
  5. bytes.fromhex(hexStr2)b'\xff\xff\xff_\x81!\x07\x0c\x00\x00\xff\xff\xff\xff_\x81)\x01\x0b'
0 0