conversion of bytes to string

python, string

Solution

Use binascii.b2a_hex (or 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'

Problem

Im reading data from an tcp connection. If I read the data from wireshark(network monitor) I get 02501c41d11ec06a471102 but if I read data in python i get it in bytes: ``` b'\x02P\x1cA\xd1\x1e\xc0jG\x11\x02' <class 'bytes'> ``` How do I convert this? I tried this: ``` #!/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) ``` but if in run this I get: ``` 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 ``` just to be clear i want to turn ``` b'\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00' ``` into ``` 02501c41d11ec06a471102 ```

Original source