1

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.

1
  • have you tried repr(data)? Commented Dec 20, 2016 at 11:17

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.