PDA

View Full Version : Convert hex to decimal



Humlan
08-11-2005, 07:13 PM
I need to convert a hexadecimal number to a decimal number, but can't figure out how to go about it.

I get seconds, minutes and hours from a DS1302 RTC chip via SHIFTIN, but the values are in hex, so I need to convert them to decimal in order to do decimal calculations with the numbers.

I've looked in all the help files, manuals and other PDFs I could find. Even a forum search for "convert hex" turns up dry.
Is this such a basic question that I'm the only one who is stumped by it? http://forums.parallax.com/images/smilies/confused.gif

I want to calculate the number of seconds since the RTC was reset. It's for an intervalometer with display, to be used with my Canon 350D camera for time-lapse photography.



HIGH CS1302
SHIFTOUT DataIO, Clock, LSBFIRST, [RdBurst]
SHIFTIN DataIO, Clock, LSBPRE, [bytRTCSecs, bytRTCMins, bytRTCHrs]

' Here I'd like to convert the hex values from the RTC chip to decimal, so the following code would work

wrdRTCSecs = (bytRTCSecs + (bytRTCMins * 60) + (bytRTCHrs * 3600))
LOW CS1302

wrdGoalSecs = 3240 ' Just an example decimal figure
wrdSecsToDisplay = wrdGoalSecs - wrdRTCSecs ' The number of seconds to be displayed

' Display the counter on the LCD
SEROUT pnLCD, conLCD, [conLCDTopHrs, DEC2 (wrdSecsToDisplay / 3600), conLCDTopMins, DEC2 ((wrdSecsToDisplay // 3600) / 60), conLCDTopSecs, DEC2 ((wrdSecsToDisplay // 3600) // 60) ]




Thanks in advance!

/Jonas

Jon Williams
08-11-2005, 08:27 PM
Convert BCD (as the DS1302 uses) to decimal and back is very easy in PBASIC:

decVal = bcdVal.NIB1 * 10 + bcdVal.NIB0
bcdVal = (decVal / 10 << 4) + (decVal // 10)

Just a not on your code, though, you are trying to store seconds in a Word -- this is not possible because there are 86,400 seconds in a day (24 x 60 x 60) and that exceeds the limit of a Word (65,535).

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Jon Williams
Applications Engineer, Parallax

Humlan
08-12-2005, 02:55 AM
Jon Williams said...
Just a not on your code, though, you are trying to store seconds in a Word -- this is not possible because there are 86,400 seconds in a day (24 x 60 x 60) and that exceeds the limit of a Word (65,535).


Thanks for the solution and the tip, but I was aware of the limit. I figure I'll put a GUI limit on 18 hours per interval, it should be more than enough.

How would one go about storing higher values? Is there an easy way to use a bit or a nibble to "extend" a word variable?

Thanks!

PS. Might I suggest a topic in the manual and the help file about conversions between the different number formats?

Jon Williams
08-12-2005, 08:10 AM
See Dr. Tracy Allen's web site for dealing with extended values: www.emesystems.com.

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Jon Williams
Applications Engineer, Parallax