Advertisement
dewabe

string_to_bcd

Aug 27th, 2015
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. # https://en.wikipedia.org/wiki/Binary-coded_decimal
  2. def string_to_bcd(string):
  3.     n = [int(c) for c in string]
  4.     bcd = [format(d, '04b') for d in n]
  5.     return bcd
  6.  
  7. bcd = string_to_bcd("402")
  8. print(bcd) # ['0100', '0000', '0010']
  9.  
  10.  
  11.  
  12.  
  13.  
  14. # UPDATED and expanded solution, allows to use also 16, 8 and 2 base and negative numbers
  15. # Also if wanted BCD as packed, possible...
  16. def to_bcd(s, packed=True):
  17.     '''
  18.    Converts 2, 8, 10 and 16 based numbers to
  19.    BCD code with sign at the end
  20.    supports values of
  21.     - packaged and unpacked
  22.     - positive and negative
  23.    not supported
  24.     - float numbers
  25.    '''
  26.     BASES = { "b": 2, "o": 8, "x": 16 }
  27.     def get_base(s):
  28.         ''' Get number system from the string '''
  29.         s.lower()
  30.         try: return BASES[s[1]]
  31.         except: return 10
  32.  
  33.     # If given value is negative, change it positive
  34.     try:
  35.         negative = True if s[0] == "-" else False
  36.         s = s[1:] if negative else s
  37.     except:
  38.         negative = True if s < 0 else False
  39.         s = s * (-1) if negative else s
  40.  
  41.     # If string, convert to integer (depending base number system)
  42.     if type(s) == str:
  43.         s = int(s, get_base(s))
  44.     elif type(s) == float:
  45.         return "Can't do float yet"
  46.  
  47.     # Make an array of every single number we have got
  48.     n = [int(c) for c in str(s)]
  49.  
  50.     # If not wanted data as packed, then adding extra 0000, make array
  51.     pack = "0000 " if not packed else ""
  52.     bcd = [pack + format(d, '04b') for d in n]
  53.  
  54.     # Add sign to the end, positive 1100 and negative 1101
  55.     sign = "1100" if not negative else "1101"
  56.     bcd.append(sign)
  57.  
  58.     # Return value as BCD coded array
  59.     return bcd
  60.  
  61. print( to_bcd("0xFFFFFF") ) # base 16
  62. print( to_bcd("0o6701") ) # base 8
  63. print( to_bcd("123") ) # base 10
  64. print( to_bcd(-623) ) # base 10, negative
  65. print( to_bcd("0b1010110", packed=False) ) # base 2, not packed
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement