#!/usr/bin/env python3
"""
Decode error codes produced by:

    #define K_ERR_APPID  (0x80000000L + 0x20000000L)
    #define K_DEF_ERR(module, level, errid) \
        ((int)((K_ERR_APPID) | ((module)<<16) | ((level)<<13) | (errid)))
"""

K_ERR_APPID = 0x80000000 + 0x20000000  # 0xA0000000


def decode_k_error(code: int):
    """Return (appid, module, level, errid) for the given error code."""
    appid = code & 0xF0000000          # top nibble (0xA0000000)
    remainder = code - appid           # lower 28 bits

    module = (remainder >> 16) & 0x0FFF
    level = (remainder >> 13) & 0x7
    errid = remainder & 0x1FFF
    return appid, module, level, errid


if __name__ == "__main__":
    val = int(input("Enter error code (decimal or 0xHEX): "), 0)
    appid, module, level, errid = decode_k_error(val)

    print(f"Error code: {val} (0x{val:X})")
    print(f"  APPID : 0x{appid:X}")
    print(f"  module: {module}")
    print(f"  level : {level}")
    print(f"  errid : {errid}")
