Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

convert HEX string to Decimal in arduino

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...