lppier
lppier

Reputation: 1987

Printing hexadecimal string in python

I'm on x86, little-endian. So I got this data from a udp packet.

data, addr = sock.recvfrom(1024)

print(data) 

gives something like '\xfe\x15'

which I understand to be the little-endian layout in memory.

The value should be represented as 0x15fe

In C i do,

printf("%x", hexvalue); 

and it gives me 0x15fe straightaway.

How do I get Python to print the hexadecimal value out properly?

Many thanks.

Upvotes: 1

Views: 12242

Answers (1)

Andrea Corbellini
Andrea Corbellini

Reputation: 17751

You can convert the bytestring to an int using struct, like this:

>>> data = b'\xfe\x15'
>>> num, = struct.unpack('<h', data)

Here <h represents a little-endian 2-bytes signed integer. Use <H if your data is unsigned. Check out the documentation for more.

Then you can print it using print(hex(num)) or similar:

>>> print(hex(num))
0x15fe

As a side note, remember that sock.recvfrom(1024) may return more or less than 2 bytes. Keep that into account when parsing.

Upvotes: 2

Related Questions