Converts a 16-binary string value to an int integer value
This example uses "1de" as the test string, the implementation code is as follows:
[CPP]View Plaincopy
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- /*
- * Convert characters to numeric values
- * */
- int c2i (char ch)
- {
- //If it is a number, subtract 48 from the ASCII code of the number if ch = ' 2 ', then ' 2 '-= 2
- if (isdigit (CH))
- return ch-48;
- //If it is a letter, but not a~f,a~f returns
- if (Ch < ' A ' | | (Ch > ' F ' && ch < ' a ') | | ch > ' z ')
- return-1;
- //If it is an uppercase letter, subtract 55 from the ASCII code of the number if ch = ' A ', then ' a '-= ten
- //If it is a lowercase letter, subtract 87 from the ASCII code of the number, if ch = ' A ', then ' a '-= ten
- if (isalpha (CH))
- return Isupper (CH)? ch-55:ch-87;
- return-1;
- }
- /*
- * Function: Convert hexadecimal string to integer (int) value
- * */
- int Hex2dec (char *hex)
- {
- int len;
- int num = 0;
- int temp;
- int bits;
- int i;
- //In this example hex = "1de" Length is 3, hex is the main function passed
- Len = strlen (hex);
- For (i=0, temp=0; i<len; i++, Temp=0)
- {
- ///First time: i=0, * (hex + i) = * (hex + 0) = ' 1 ', i.e. temp = 1
- ///second time: I=1, * (hex + i) = * (hex + 1) = ' d ', i.e. temp =
- //Third: i=2, * (hex + i) = * (hex + 2) = ' d ', i.e. temp =
- temp = c2i (* (hex + i));
- //Total 3 bits, one 16 binary bit saved with 4 bit
- ///First: ' 1 ' is the highest bit, so temp shifts left (len-i-1) * 4 = 2 * 4 = 8-bit
- ///second: ' d ' is a secondary high, so temp shifts left (len-i-1) * 4 = 1 * 4 = 4-bit
- //Third: ' E ' is the lowest bit, so temp shifts left (len-i-1) * 4 = 0 * 4 = 0-bit
- Bits = (Len-i-1) * 4;
- temp = temp << bits;
- //You can also use num + = temp here;
- num = num | Temp
- }
- //Return results
- return num;
- }
- int main (int argc, char *argv[])
- {
- char ch[10] = {0};
- strcpy (CH, "1de");
- printf ("hex:%d\n", Hex2dec (CH));
- return 0;
- }
I tested at CentOS 6.5
Compilation: Gcc-wall Test.c-ohex
Run:./hex
Output: hex:478
C language: Convert 16 binary string to int type value