python3:各种转换

来源:互联网 发布:win10深度系统优化 编辑:程序博客网 时间:2024/05/21 00:55


'''[int(x) for x in bytes(ser.read_all())]''''''[hex(x) for x in bytes(ser.read_all())]''''''10进制数字转16进制 hex(10) '0xa' 再转成bytes: hex(10).encode('utf-8') b'0xa' 16进制数字转10进制 int(0x0a) 10 int('10') 10 int('0xa',16) 10 int(b'0xa',16) 10字符转bytes:用 .encode('utf-8')bytes转字符:用 .decode()一个数字,只保留16进制的最后两个值:'''def i_to_b(int):#10进制转16进制后转bytes     return hex(int).encode('utf-8')def b_to_i(byte):#一个bytes转成int数字     return int(byte,16)def HexToByte( hexStr ):     if(hexStr[0:2])=='0x':         hexStr = hexStr[2:len(hexStr)]     if len(hexStr) == 1:         hexStr = '0' + hexStr     return bytes.fromhex(hexStr)

bytes object   b = b"example"     str object   s = "example"      #str to bytes     bytes(s, encoding = "utf8")     #bytes to str     str(b, encoding = "utf-8")    #an alternative method     #str to bytes     str.encode(s)     #bytes to str     bytes.decode(b)  


0 0
原创粉丝点击