-2

I'm trying to confirm this struct is being formatted correctly for network byte order, but printing out the bytes and printing out the hex of the bytes give me different output, with the hex being the expected output. But I don't know why they are different.

import ctypes

class test_struct(ctypes.BigEndianStructure):
    _pack_ = 1
    _fields_ = [ ('f1', ctypes.c_ushort, 16) ]

foo = test_struct()
foo.f1 = 0x8043
bs = bytes(foo)
print(str(bs[0:1]) + " " + str(bs[1:2]))
print(bs.hex(' '))

The output is

b'\x80' b'C'
80 43
1
  • 3
    It seems that the first output is correct too. C is 0x43 in ASCII. print() needs to be changed to print hex output. Try using this: print("{0:02x} {1:02x}".format(bs[0],bs[1])) instead of print(str(bs[0:1]) + " " + str(bs[1:2])). Check this thread for more options: stackoverflow.com/q/16572008/26993270 Commented Oct 30, 2024 at 1:22

1 Answer 1

2

The order is correct. The difference is how the bytes are displayed.

A bytes object's default display is b'X' where X is either the printable ASCII character for that byte, an escape character (\t\r\n) or a hexadecimal escape (\xhh).

If a bytes object is iterated, the values are integers 0-255. Those integers can be displayed in any way you like, e.g.:

import ctypes

class test_struct(ctypes.BigEndianStructure):
    _fields_ = ('f1', ctypes.c_ushort),

foo = test_struct(0x8043)
for b in bytes(foo):
    # decimal integer (default), hexadecimal integer, and 1-byte `bytes` object.
    print(f'{b:3} 0x{b:02x} {bytes([b])}')

Output:

128 0x80 b'\x80'
 67 0x43 b'C'
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.