lukesmith
lukesmith

Reputation: 3

Python struct.pack dropping a byte.

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?

Upvotes: 0

Views: 615

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121256

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'

Upvotes: 3

Related Questions