Created
May 2, 2012 19:39
-
-
Save rtirrell/2579635 to your computer and use it in GitHub Desktop.
BCD utils
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def bcd_to_int(bcd_int): | |
'''Convert a BCD integer to a base-10 integer.''' | |
bcd_str = bin(bcd_int)[2:][::-1] | |
num_groups = ((len(bcd_str) - 1) / 4) + 1 | |
total = 0 | |
for i in range(num_groups): | |
digit = bcd_str[(4 * i):(4 * (i + 1))][::-1] | |
total += int(digit, 2) * (10 ** i) | |
return total | |
def int_to_bcd(dec_val): | |
'''Convert a base-10 integer to a BCD integer.''' | |
dec_val = str(dec_val) | |
bin_str = '' | |
for digit in dec_val: | |
bin_digit = bin(int(digit))[2:] | |
bin_str = bin_str + '0' * (4 - len(bin_digit)) + bin_digit | |
return int(bin_str, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment