In actual work, the conversion of strings and other data types is very common, there are many library functions, such as atoi , strtol ,sscanf , and so on, these functions online has a lot of information,
What I often use is that hexadecimal values are transmitted as strings and then parsed, and here's what I'm doing here:
Converts a 2-byte hexadecimal string into a short int with 2 bytes of shaping data:
Writing is not easy, reproduced please specify the source: http://blog.csdn.net/jscese/article/details/39054969
Short int xstrtoshortint (char *str) { //int len=strlen (str); short int ivalue = 0; This translates to 2 bytes of shaped number if ((LEN/2) >sizeof (ivalue)) { printf ("Left overflow \ n");//Will overflow } int Ioffset = 0; Shift char *ptr;//character pointer ptr = str;//start from scratch while (*ptr! = ') //To the last string Terminator { Ivalue = Ivalue << Ioffset; The first time does not shift, after each shift left 4bit, hexadecimal one character represents 4bit if ((*ptr <= ' 9 ' && *ptr >= ' 0 ')) { ivalue = ivalue + (*p TR-' 0 '); } else if ((*ptr >= ' a ' && *ptr <= ' F ')) { ivalue = ivalue + (*ptr-' a ') +; } else if ((*ptr >= ' a ' && *ptr <= ' F ')) { ivalue = ivalue + (*ptr-' a ') +; } To ivalue low 4bit assignment value ptr++; Ioffset = 4; } return ivalue;}
You can also do this, the principle is the same, just another way:
Short int xstrtoshortint (char *str) { int len = strlen (str); short int ivalue = 0; for (int i = 0; i < len; i++) { if ((Str[i] <= ' 9 ' && str[i] >= ' 0 ')) { Ivalue = Ivalue * + (Str[i]-' 0 '); 16 binary convertible Other binary } else if ((Str[i] >= ' A ' && str[i] <= ' F ')) { Ivalue = Ivalue * + (Str[i] -' a ') + Ten; } else if ((Str[i] >= ' A ' && str[i] <= ' F ') { Ivalue = Ivalue * + + (Str[i]-' a ') +; } } return ivalue;}
For example, call Xstrtoshortint ("1a4e"), you can get a 0x1a4e short int data, if you want to go to other data types, the principle is similar!
Thesprintf function is most commonly used when you turn a string.
c/c++--conversion of hexadecimal type strings