Hubert S. Cumberdale Hubert S. Cumberdale - 2 months ago 18
Python Question

Data from socket.recv() printing as a mixture of \x and printable ASCII, how to force raw hex?

I have some simple code which is listening to data on a TCP socket:

data = client_socket.recv(4096)
print("RECEIVED:",data)


It works great, but the output looks like this:

RECEIVED: b'\xd8\xff\xfe\x00$\xe3J\xda*\x00


and so on.

What I want is just the raw hex, like

D8 FF FE 00 24 E3 4A DA 2A 00


My end goal is to put the raw bytes straight into a file, but I do want to print them first. How do I print them as I desire, and how do I put them into a file? Maybe I do not even need to manipulate 'data' to put it in a file?

Thanks very much!

Answer
import binascii
binascii.hexlify('\xd8\xff\xfe\x00$\xe3J\xda*\x00').upper()

gets you most of the way ...