【Python3數據處理】數據轉換 bytes/string/ASCII/GBK...

Python3 應用在做數據解析時,常常用到的數據類型是:字節,字符串,列表,字典(轉json)
數據編碼格式不同,數據存入的字節數組也會有所不同。

常用的數據編碼格式,ASCII碼,GBK編碼,UTF8編碼


數據轉換參考示例

以下示例僅供參考,性能高低以實際測試情況爲準,這裏只考慮能否實現數據轉換

1、字節(bytes)轉字符串(str)

rec_msg = b'\x12\x55\xaa\xFF\x55\x34'
out_s = ''  
for i in range(0, len(rec_msg)):     # 獲取字節數組字數據,注意引號 ' ' 之間有一個空格
    out_s = out_s + ' ' + (hex(int(rec_msg[i]))).upper()[2:].zfill(2)
    
print(out_s)    # >>> 12 55 AA FF 55 34

轉換原理解析:分離出byte,轉爲int(), 再hex()轉回16進制數後截取0x前綴,再遍歷拼接成字符串

2、字符串(str)轉爲字節數組

hex_string = '01 02 27 11 00 08'            # 模擬請求讀取DISCRETE信息的指令(未加crc值)
heartbeat = bytearray.fromhex(hex_string)
print(heartbeat)    # >>> bytearray(b"\x01\x02\'\x11\x00\x08")

3、int轉爲16進制字符串

hex(10)  # >> 0xa, type=str

4、16進制字符串轉爲int

int(hex(12), 16)    # 12
int('FF', 16)       # 255
int('FFEF', 16)     # 65519

5、16進制字符串 / int 轉爲2進制字符串

bin(int('FF', 16))     # >>> '0b11111111'
bin(0)[2:].zfill(8)    # >>> '00000000'

6、列表轉爲字符串

register_list = [1, 2, 3, 4,]
str_set = ''
for i in range(len(register_list)):
    str_set = str_set + register_list[i] + ' '

7、按空格截取字符串轉到列表

out_s = '12 22 34 45 56'
out_s.split()    # 按空格截取字符串轉到列表裏面
# >>> ['12', '22', '34', '45', '56']

8、GBK編碼格式的字符串(中文)轉爲 bytes 和16進制字符串

GBK編碼: ( 1箇中文對應2個byte)

a = '與'
a.encode('GBK')         # b'\xd3\xeb'
type(a.encode('GBK'))   # <class 'bytes'>

print('{}'.format(a.encode('GBK')).replace("b'\\x", '').replace('\\x', '').replace("'", '').strip().upper())
# 'D3EB'

9、bytes / bytearray / 16進制字符串 轉爲GBK編碼的字符串(中文)

a = b'\xbf\xc6'             # bytes
print(a.decode('GBK'))      # '科'


b = 'bfc6 bfc6'             # bytes
b = bytearray.fromhex(b)    # bytearray
c = b.decode('GBK')         # str() 字符串(中文)
print('c:', c)              #  c: 科科

10、UTF-8編碼格式也使用相同的方法轉換

a = '中國'
b = a.encode('utf-8')      # b'\xe4\xb8\xad\xe5\x9b\xbd'

d = b'\xe4\xb8\xad\xe5\x9b\xbd'
d.decode('utf-8')          # '中國'

11、ASCII碼轉換

a = 't'
ord(a)         # 116
hex(ord(a))    # '0x74'


chr() 可以直接用16進制數或者 int 轉換爲對應的ASCII碼字符
a = 0x30
chr(a)         # '0'
chr(48)        # '0'

12、8進制字符串 / byte 轉換

oct(10)           # '0o12'
int(b'0o12', 8)   # 10
int('12', 8)      # 10

13、交叉轉換,如既有GBK編碼和ASCII編碼的字符串轉爲16進制字符串

❌錯誤示例

a = 'Python3數據轉換test'
a.encode('GBK')    # b'Python3\xca\xfd\xbe\xdd\xd7\xaa\xbb\xbbtest'

如上,單純使用GBK編碼不能將非中文字符轉爲對應的16進制的byte,
此時,可以將字符串拆分出來,一個一個轉換

lst = []
for i in range(len(a)):
    lst.append(hex(ord(a[i]))[2:])
lst    # ['50', '79', '74', '68', '6f', '6e', '33', '6570', '636e', '8f6c', '6362', '74', '65', '73', '74']

可以發現ord()轉換後,中文佔用2個字節,英文佔用1個字節

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章