diff --git a/dcd/bit.py b/dcd/bit.py index 5a610ec..1031f8d 100644 --- a/dcd/bit.py +++ b/dcd/bit.py @@ -56,3 +56,22 @@ def hex_to_raw(text, separator=" "): output.append(int(text[2*i:2*i+2], 16)) return bytearray(output) + +def raw_to_bcd(raw): + """ + Decodes a bytearray (or bytes) to an integer as BCD. + """ + + sum = 0 + order = 1 + + for byte in reversed(raw): + sum += (byte & 0x0f) * order + order *= 10 + sum += (byte >> 4) * order + order *= 10 + + return sum + +def hex_to_bcd(text): + return raw_to_bcd(hex_to_raw(text))