Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # https://en.wikipedia.org/wiki/Binary-coded_decimal
- def string_to_bcd(string):
- n = [int(c) for c in string]
- bcd = [format(d, '04b') for d in n]
- return bcd
- bcd = string_to_bcd("402")
- print(bcd) # ['0100', '0000', '0010']
- # UPDATED and expanded solution, allows to use also 16, 8 and 2 base and negative numbers
- # Also if wanted BCD as packed, possible...
- def to_bcd(s, packed=True):
- '''
- Converts 2, 8, 10 and 16 based numbers to
- BCD code with sign at the end
- supports values of
- - packaged and unpacked
- - positive and negative
- not supported
- - float numbers
- '''
- BASES = { "b": 2, "o": 8, "x": 16 }
- def get_base(s):
- ''' Get number system from the string '''
- s.lower()
- try: return BASES[s[1]]
- except: return 10
- # If given value is negative, change it positive
- try:
- negative = True if s[0] == "-" else False
- s = s[1:] if negative else s
- except:
- negative = True if s < 0 else False
- s = s * (-1) if negative else s
- # If string, convert to integer (depending base number system)
- if type(s) == str:
- s = int(s, get_base(s))
- elif type(s) == float:
- return "Can't do float yet"
- # Make an array of every single number we have got
- n = [int(c) for c in str(s)]
- # If not wanted data as packed, then adding extra 0000, make array
- pack = "0000 " if not packed else ""
- bcd = [pack + format(d, '04b') for d in n]
- # Add sign to the end, positive 1100 and negative 1101
- sign = "1100" if not negative else "1101"
- bcd.append(sign)
- # Return value as BCD coded array
- return bcd
- print( to_bcd("0xFFFFFF") ) # base 16
- print( to_bcd("0o6701") ) # base 8
- print( to_bcd("123") ) # base 10
- print( to_bcd(-623) ) # base 10, negative
- print( to_bcd("0b1010110", packed=False) ) # base 2, not packed
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement