Search code examples
pythonctypes

How can I tell if a ctypes integer type is big endian?


Consider the following:

le = ctypes.c_uint32.__ctype_le__
be = ctypes.c_uint16.__ctype_be__

How can I write a function is_bigendian(cls) that behaves as you would expect:

>>> is_bigendian(le)
False
>>> is_bigendian(be)
True

Does ctypes expose this information somewhere?


Solution

  • It seems the only possible way is:

    if ctypes.c_uint8.__ctype_be__.__name__.endswith('_be'):
        def is_bigendian(cls):
            return cls.__name__.endswith('_be')
    elif ctypes.c_uint8.__ctype_le__.__name__.endswith('_le'):
        def is_bigendian(cls):
            return not cls.__name__.endswith('_le')
    else:
        raise RuntimeError
    

    Which is hard to spot, because repr(ctypes.c_uint8.__ctype_be__) doesn't show the class name correctly.