pythonhexbyte

Why does hex give a different output than indexing into bytes in python?


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

Solution

  • 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'