0

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
asked Oct 11, 2013 at 15:50

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.