Convert a hex value to dec
Mike2545
Posts: 433
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....
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
date = 10*(date >>4) + (date & $0f)
can also be written as,
date = 10 * date.nib1 + date.nib0
date= (((date/ 10) << 4) + (date // 10))
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