/******************************************************************************/ /* * convert a hex string to an integer. The end of the string or a non-hex * character will indicate the end of the hex specification. */
unsigned int hextoi(char*hexstring) { register char*h; register unsigned int c, v;
v =0; h = hexstring; if (*h =='0'&& (*(h+1) =='x'||*(h+1) =='X')) { h +=2; } while ((c = (unsigned int)*h++) !=0) { if (c >='0'&& c <='9') { c -='0'; } elseif (c >='a'&& c <='f') { c = (c -'a') +10; } elseif (c >='A'&& c <='F') { c = (c -'A') +10; } else { break; } v = (v *0x10) + c; } return v; }
在VC中测试如下:
View Code
1#include<iostream.h> 2 3/******************************************************************************/ 4/* 5 * convert a hex string to an integer. The end of the string or a non-hex 6 * character will indicate the end of the hex specification. 7*/ 8 9unsigned int hextoi(char*hexstring) 10{ 11 register char*h; 12 register unsigned int c, v; 13 14 v =0; 15 h = hexstring; 16if (*h =='0'&& (*(h+1) =='x'||*(h+1) =='X')) { 17 h +=2; 18 } 19while ((c = (unsigned int)*h++) !=0) { 20if (c >='0'&& c <='9') { 21 c -='0'; 22 } elseif (c >='a'&& c <='f') { 23 c = (c -'a') +10; 24 } elseif (c >='A'&& c <='F') { 25 c = (c -'A') +10; 26 } else { 27break; 28 } 29 v = (v *0x10) + c; 30 } 31return v; 32} 33 34void main() 35{ 36char test[20]; 37 cin>>test; 38 cout<<hextoi(test)<<endl; 39}
文章评论(0条评论)
登录后参与讨论