牛骨文教育服务平台(让学习变的简单)
博文笔记

python str byte hex

创建时间:2017-04-19 投稿人: 浏览次数:851
最近遇到的问题      网络传输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"xffxffxff_x81!x07x0cx00x00xffxffxffxff_x81)x01x0b"
    
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。