Defining char types

Hi, I'm running this code to convert a date from individual char types to one dec number.
unsigned long date_convert() { //converts 6 ascii digits in eprom_date array into integer returned

When my input is > 39999 I get a huge incorrect final value out. I need to convert up to 92000.

I'm really messing with caller ID dates but I think for our purposes it doesn't matter.

I feel like the unsigned long should be ok.
Any help would be appreciated.

 unsigned long retval = 0;   //

  eprom_date[0] = '3';    // test values  (want to go up to 92000 here
  eprom_date[1] = '9';
  eprom_date[2] = '9';
  eprom_date[3] = '9';
  eprom_date[4] = '9';

  retval =  (eprom_date[0]  - 0x30)  * 10000;  // year ones
  retval +=  (eprom_date[1]  - 0x30)  * 1000;  // month tens
  retval +=  (eprom_date[2]  - 0x30)  * 100;   // month ones
  retval +=  (eprom_date[3]  - 0x30)  * 10;    // day tens
  retval +=  (eprom_date[4]  - 0x30);          // day ones

  Serial.print("Date Convert= ");    Serial.println(retval, DEC);   // expect 39999 here
  return (retval);

Don't post snippets (Snippets R Us!)

Your math such as (eprom_date[0] - 0x30) * 10000; is conducted using int
an int on an 8 bit microcontroller goes to 32767
if you want to make that unsigned long math, you need to force the data type adding ul to the literals for example

  retval =  (eprom_date[0]  - 0x30ul)  * 10000ul;  // year ones
1 Like

This is all of the code except the void date_convert () { } at the end.

I edited my post whilst you were typing

(still don't post snippets, for example we don't know the type and size of the eprom_date array)

You're right. I know the array sizes are OK but should have shown it.

The "UL"'s worked. Thanks very much. !

great :slight_smile:

have fun

PS/

probably more readable as

  retval  =  (eprom_date[0]  - '0')  * 10000ul;  // year ones
  retval +=  (eprom_date[1]  - '0')  * 1000ul;   // month tens
  retval +=  (eprom_date[2]  - '0')  * 100ul;    // month ones
  retval +=  (eprom_date[3]  - '0')  * 10ul;     // day tens
  retval +=  (eprom_date[4]  - '0');             // day ones

PS2/ you'd probably be better off to store the unsigned long in EEPROM rather than the ASCII representation and use get() and put()

That is easier to read. Thanks for the tip.

unsigned long retval = 0;   //

  eprom_date[0] = '3';    // test values  (want to go up to 92000 here
  eprom_date[1] = '9';
  eprom_date[2] = '9';
  eprom_date[3] = '9';
  eprom_date[4] = '9';

  for (byte i=0;i<4;i++)retval = (eprom_date[i] - '0') + retval * 10;
  
  Serial.print("Date Convert= ");    Serial.println(retval, DEC);   // expect 39999 here
  return (retval);

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.