/*************************************** * ********************************** Type: <c programming language (version 2. new Version)> Exercise 2-3 name: lx. c author: wubenzhimu data: 2012.11.16 function: Compile the htio (s) function to include a string consisting of hexadecimal numbers (including optional prefixes 0x or 0X) to an equivalent integer. The numbers that can be contained in a string include 0-9, A-f, and a-F. **************************************** * **********************************/# Include <stdio. h> # include <stdlib. h> unsigned int htoi (const char s []); int hexalpha_to_int (int c); int main (void) {/* define pointer */char * endp = NULL; char * test [] = {"F00", "bar", "0100", "0x1", "0XA", "0X0c0BE", "abcdef ", "123456", "0x123456", "deadbeef", "zog_c"}; unsigned int result; unsigned int check;/*** size_t is predefined in c A type of * size_t numtests = unsigned int numtests * determines the number of arrays */size_t numtests = sizeof test/sizeof test [0]; size_t thistest; for (thistest = 0; thistest <numtests; thistest ++) {result = htoi (test [thistest]);/*** unsigned long int strtoul (const char * nptr, char * endptr, int base); * (converts a string to an unsigned long integer number) */check = (unsigned int) strtoul (test [thistest], & endp, 16 ); if (* endp! = '\ 0' | result = check) & result! = 0) {printf ("test (Testing) % s. correct (Correct ). % u \ n ", test [thistest], result);} else {printf (" test (Testing) % s. error (Incorrect ). % u \ n ", test [thistest], result) ;}return 0 ;}/ *** convert binary in decimal format * the first value of the method x 16 to the power of 0, the second value is * 16 to the power of 1 .... All values are added in decimal number */unsigned int htoi (const char s []) {unsigned int answer = 0; int I = 0; int valid = 1; int hexit;/*** hexadecimal: * starting with 0x or 0X * Here, determine whether char s [] is in hexadecimal format */if (s [I] = '0') {++ I; if (s [I] = 'X' | s [I] = 'X') {++ I ;}} while (valid & s [I]! = '\ 0') {answer = answer * 16; if (s [I]> = '0' & s [I] <= '9 ') {answer = answer + (s [I]-'0');} else {hexit = hexalpha_to_int (s [I]); if (hexit = 0) {valid = 0 ;}else {answer = answer + hexit ;}}++ I ;}if (! Valid) {answer = 0;} return answer;}/*** function implementation: hexadecimal characters include enabling this method in a-f or A-F */int hexalpha_to_int (int c) {char hexalpha [] = "aAbBcCdDeEfF"; int I; int answer = 0; for (I = 0; answer = 0 & hexalpha [I]! = '\ 0'; I ++) {if (hexalpha [I] = c) {answer = 10 + (I/2) ;}} return answer ;}
Super programs, writing by yourself is still a bit of a problem .. Some program changes
Result: