一、字符串轉bytespython
string to bytes eg: '0123456789ABCDEF0123456789ABCDEF' b'0123456789ABCDEF0123456789ABCDEF' def stringTobytes(str): return bytes(str,encoding='utf8')
二、bytes轉字符串ide
bytes to string eg: b'0123456789ABCDEF0123456789ABCDEF' '0123456789ABCDEF0123456789ABCDEF' def bytesToString(bs): return bytes.decode(bs,encoding='utf8')
三、十六進制字符串轉bytesspa
hex string to bytes eg: '01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF' b'\x01#Eg\x89\xab\xcd\xef\x01#Eg\x89\xab\xcd\xef' def hexStringTobytes(str): str = str.replace(" ", "") return bytes.fromhex(str) # return a2b_hex(str)
四、bytes轉十六進制字符串code
bytes to hex string eg: b'\x01#Eg\x89\xab\xcd\xef\x01#Eg\x89\xab\xcd\xef' '01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF' def bytesToHexString(bs): # hex_str = '' # for item in bs: # hex_str += str(hex(item))[2:].zfill(2).upper() + " " # return hex_str return ''.join(['%02X ' % b for b in bs])
輸出最小寬度
用十進制整數來表示輸出的最少位數。若實際位數多於定義的寬度,則按實際位數輸出,若實際位數少於定義的寬度則補以空格或0(當最小寬度數值以0開頭時)。字符串
X 表示以十六進制形式輸出
02 表示不足兩位,前面補0輸出;若是超過兩位,則實際輸出
舉例:string
printf("%02X", 0x345); //打印出:345 printf("%02X", 0x6); //打印出:06
而若是直接寫爲 %2x,數據不足兩位時,實際輸出,即不額外補0輸出; 若是超過兩位,則實際輸出。it
printf("%2X", 0x345); //打印出:345 printf("%2X", 0x6); //打印出:6