If I run the following using Python 3.3.1:
import struct
struct.pack('!Bhh', 1, 1, 10)
I get this result:
b'\x01\x00\x01\x00\n'
rather than the result I am expecting:
b'\x01\x00\x01\x00\x0a\n'
Can anyone tell me where my missing byte has gone?
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.5k bronze badges
1 Answer 1
Your lost byte is right there; \n is character 10 in the ASCII table:
>>> chr(10)
'\n'
Instead of displaying it as \x0a it is displayed as a Python string literal escape code; other known escapes are also shown that way. Printable ASCII characters are shown as characters:
>>> struct.pack('!Bhh', 1, 1, 13)
b'\x01\x00\x01\x00\r'
>>> struct.pack('!Bhh', 1, 1, 9)
b'\x01\x00\x01\x00\t'
>>> struct.pack('!Bhh', 1, 1, 65)
b'\x01\x00\x01\x00A'
It might help to use binascii.hexlify() to convert your bytes to hexadecimal characters:
>>> from binascii import hexlify
>>> hexlify(struct.pack('!Bhh', 1, 1, 10))
b'010001000a'
answered Oct 11, 2013 at 15:52
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.5k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py