Python, how to decode Binary coded decimal (BCD)

Viewed 23386

Description of the binary field is:

Caller number, expressed with compressed BCD code, and the surplus bits are filled with “0xF”

I have tried to print with struct format '16c' and I get: ('3', '\x00', '\x02', '\x05', '\x15', '\x13', 'G', 'O', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff') and if I use '16b' i get (51, 0, 2, 5, 21, 19, 71, 79, -1, -1, -1, -1, -1, -1, -1, -1). And it is not correct, I should get phone number, and numbers above are invalid.

print struct.unpack_from('>16b', str(data.read()),offset=46)

Above is code that didn't work and I get invalid numbers. With what format should I unpack that 16 byte field and how to convert BCD code ?

3 Answers
a = b'\x12\x34\x5f'

def comp3_to_int(a):
    b = a.hex()
    c = int(b[0:len(b)-1])
    if b[len(b)-1:] == 'd':
        c = -c
    return c

Function from my project. Second argument places decimal point.

def bcd_decode(data: bytes, decimals: int):
    '''
    Decode BCD number
    '''
    res = 0
    for n, b in enumerate(reversed(data)):
        res += (b & 0x0F) * 10 ** (n * 2 - decimals)
        res += (b >> 4) * 10 ** (n * 2 + 1 - decimals)
    return res
Related