Shop OBEX P1 Docs P2 Docs Learn Events
Good BCD to Decimal code? — Parallax Forums

Good BCD to Decimal code?

RavenkallenRavenkallen Posts: 1,057
edited 2010-12-13 20:17 in Propeller 1
I am looking for an efficient way to make a routine that will be able to convert a bcd value(0-255) to decimal. My current coding uses a ton of IF statements to get the job done and it is slow. Does anybody have a simple snippet of a method that can convert between the two? Just a little something to get me back on track. It is probably really trivial, but i am just having a hard time visualizing it..

Comments

  • kuronekokuroneko Posts: 3,623
    edited 2010-12-12 18:29
    Provided I understood your requirement correctly (3 digit BCD):
    PUB BCD2DEC(bcd)
    
      return (bcd >> 8) * 100 + ((bcd >> 4) & %1111) * 10 + (bcd & %1111)
    
  • RavenkallenRavenkallen Posts: 1,057
    edited 2010-12-12 18:44
    Oh, sorry. Forgot the details :)
    It is 1 digit for every four bits(So each byte contains 2 digits) . It is the format commonly used in RTC's . So i need to convert a number that holds 2 bcd digits to a single byte value
  • MagIO2MagIO2 Posts: 2,243
    edited 2010-12-13 10:16
    These details do not describe anything which is not normal for BCD. This is what BCD means in common sense.

    And Kuronekos code is correct if you call the function correctly. It only allows you to call it with $0000_00_00 - $0000_09_99. In your special case you only want to call it with $000-$255, so that should not be a problem.

    What kuronekos code is doing for example with number $128:

    $128 >> 8 = 1
    1*100=100
    $128>>4 = $12
    $12 & %1111 = 2
    2*10=20
    $128 & %1111 = 8
    and finally 100 + 20 + 8 = 128 = $80
  • Roy ElthamRoy Eltham Posts: 3,000
    edited 2010-12-13 10:29
    Here is the 2 digit version:
    PUB BCD2DEC(bcd)
      return ((bcd >> 4) & %1111) * 10 + (bcd & %1111)
    
  • RavenkallenRavenkallen Posts: 1,057
    edited 2010-12-13 14:06
    Thanks for the help guys. I will try out the code once i can get my rtc back up(It's acting weird). I think i understand the principle behind it, but bcd numbers have always confused me. So basically you are shifting some of the number and adding %1111 in binary, and depending on the digit, multiplying it?
  • JonnyMacJonnyMac Posts: 9,208
    edited 2010-12-13 14:35
    The ANDing with %1111 is to isolate the nibbles. The upper nibble is the 10s digit so it gets multiplied by 10. The lower nibble is the 1s digit and only needs isolation from the other bits in the byte.
  • RavenkallenRavenkallen Posts: 1,057
    edited 2010-12-13 20:17
    I think i got it know. I will give it a go soon!
Sign In or Register to comment.