-1

I'm using python and need to find out the following to finish off a converter, How to convert either binary/denary/hexadecimal/octal to Binary Coded Decimal (BCD) in python

Cowie
  • 1
  • 1

1 Answers1

0

BCD is actually pretty simple. Depends on what you want the end format in though.

unpacked:

def to_bcd(number):
    return [ord(x)-ord('0') for x in '%d'%number]

packed is slightly more work:

def to_packed_bcd(number):
    numtest = '%d'%number
    if len(numtest)%2 == 1:
        numtest = '0%s'%numtest
    return [(ord(numtest[x])-ord('0'))<<4 | (ord(numtest[x+1])-ord('0')) for x in range(0, len(numtest), 2)]

x
Corley Brigman
  • 11,633
  • 5
  • 33
  • 40