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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.