2

i have an Hex String like this : "0005607947" and want to convert it to Decimal number , i test it on this site and it correctly convert to decimal number and answer is : "90208583" but when i use this code i get wrong value ! where of my code is wrong or did have any one , some new code for this problem ?

long int decimal_answer = getDEC("0005607947") ;

long int getDEC(String str110) {
   long int ID = 0 ;
   int len = str110.length() ;
   char buff[len] ;
   int power = 0 ;

   for(int i = 0 ; i <len ; i++) {  buff[i] = str110.charAt(i); }

   for(int i = (len-1) ; i >=0 ; i--) { 
      int num = buff[i] - '0' ;
      ID = ID + num * pow(16 , power) ;
      power = power + 1 ;   
     }
    Serial.println(String(ID , DEC));
  return ID ;
}



// thanks , i also use this but , get error : invalid conversion from 'void*' to  'char**' [-fpermissive]
unsigned int SiZe = sizeof(F_value) ;
char charBuf[SiZe];
F_value.toCharArray(charBuf , SiZe);

long decimal_answer = strtol(charBuf , NULL , 16);
Serial.println(decimal_answer , DEC);
hkh114
  • 162
  • 1
  • 3
  • 15

2 Answers2

5

Drop all that code, and just use 'strtol' from the standard library.

 #include <stdlib.h>
 long strtol (const char *__nptr, char **__endptr, int __base)

For your use:

long decimal_answer = strtol("0005607947", NULL, 16);
0

You are trying to store the value 90208583 in an int. Arduino has a 2 byte int size meaning that the largest number you can store is 2^16-1 (65535). You have a couple of options:

  1. Use an unsigned int
    • min number: 0
    • max number: 4,294,967,295
    • cons: can only be used for positive numbers
  2. Use a long int
    • min number: -2,147,483,648
    • max number: 2,147,483,647
torrey1028
  • 19
  • 1
  • , i changed it to 'long' but the 5 first digit is correct but the rest is incorrect !! the new answer is : 90208464 (correct : 90208583) – hkh114 Aug 09 '15 at 10:59