将字节转换为字符串

时间:2013-08-04 12:08:37

标签: python string

我正在从tcp连接中读取数据。如果我从wireshark(网络监视器)读取数据,我得到02501c41d11ec06a471102,但如果我在python中读取数据,我会以字节为单位获取数据:

b'\x02P\x1cA\xd1\x1e\xc0jG\x11\x02'
<class 'bytes'>

我该如何转换? 我试过这个:

#!/usr/bin/env python

import socket
import binascii
import time
import sys

TCP_IP = '10.20.0.195'
TCP_PORT = 9761
BUFFER_SIZE = 2048

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))

while 1:
    data = s.recv(1024)
    print (data)
    data2 = data.decode("utf-8")
    typ = type(data)
    print (typ)

但如果在运行中我得到:

b'\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00'
Traceback (most recent call last):
  File "Z:/programeren/domotica/try again/receive.py", line 18, in <module>
    data2 = data.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 4: invalid continuation byte

要明确我想转

b'\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00'

02501c41d11ec06a471102

1 个答案:

答案 0 :(得分:3)

使用binascii.b2a_hex(或binascii.hexlify)。

>>> import binascii
>>> binascii.b2a_hex(b'\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00')
b'02501c41d1000002cb1100'
>>> binascii.b2a_hex(b'\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00').decode('ascii')
'02501c41d1000002cb1100'