Shop OBEX P1 Docs P2 Docs Learn Events
Convert a hex value to dec — Parallax Forums

Convert a hex value to dec

Mike2545Mike2545 Posts: 433
edited 2011-10-07 09:06 in BASIC Stamp
I have worked with a RTC (real time clock) DS1340C and the I2c input/ output are in Hex. If you try to do math on the number you get an undesired result. For instance the date 1/31/11 is 1/49/B. And the time...dont get me started on the time.

Well a friend helped me out, I thought I would share with you.

date = 10*(date >>4) + (date & $0f)

That bit of code will take Hex 31 and turn it into Dec 31 not the usual Dec 49
Maybe its in some documentation somewhere and I missed it....

Comments

  • Tracy AllenTracy Allen Posts: 6,662
    edited 2011-10-06 18:06
    The Stamp also has nibbles, so
    date = 10*(date >>4) + (date & $0f)
    can also be written as,
    date = 10 * date.nib1 + date.nib0
  • Mike2545Mike2545 Posts: 433
    edited 2011-10-06 18:13
    How do you do the reverse...make a dec a hex?

    date= (((date/ 10) << 4) + (date // 10))
  • Tracy AllenTracy Allen Posts: 6,662
    edited 2011-10-07 08:49
    Technically it is BCD (binary coded decimal) that you are talking about. It looks like hex and can be displayed correctly using the serial HEX modifier.
    example:
    --$54 in hex is the same as the decimal number 84 and both of those are represented in binary by the same integer value, binary %01011000.
    --$54 in BCD is a representation of the decimal value 54, but inside the cpu it is still stored as the above integer value. And the conversion to decimal is 10 * 5 + 4 = 54, which is then stored in memory as 54 = $36 = %00110110
  • Mike2545Mike2545 Posts: 433
    edited 2011-10-07 09:06
    Yes BCD, and true that you can display the hex number correctly with the HEX modifier but if you need to do math on the number as hex you come up with undesired results. For instance, first post in this thread, Hex 31 is Dec 49, but you actually want 31 to be able to figure the day of the year or in some instances with this RTC adjust the time. If you start going something like "minute = minute +1", in a button press routine, with a hex number things go sideways. You need to change it to a BCD in order to do that sort of operation on the variabel.
Sign In or Register to comment.