/******************************************************************************/
/*
* 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';
}
else if (c >= 'a' && c <= 'f') {
c
= (c - 'a') + 10;
}
else if (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
9 unsigned int hextoi(char *hexstring)
10 {
11 register char *h;
12 register unsigned int c, v;
13
14 v = 0;
15 h = hexstring;
16 if (*h == '0' && (*(h+1) == 'x' || *(h+1) == 'X')) {
17 h += 2;
18 }
19 while ((c = (unsigned int)*h++) != 0) {
20 if (c >= '0' && c <= '9') {
21 c -= '0';
22 } else if (c >= 'a' && c <= 'f') {
23 c = (c - 'a') + 10;
24 } else if (c >= 'A' && c <= 'F') {
25 c = (c - 'A') + 10;
26 } else {
27 break;
28 }
29 v = (v * 0x10) + c;
30 }
31 return v;
32 }
33
34 void main()
35 {
36 char test[20];
37 cin>>test;
38 cout<<hextoi(test)<<endl;
39 }

运行结果符合要求。

相关文章:

  • 2021-12-25
  • 2022-12-23
  • 2022-12-23
  • 2021-12-08
  • 2022-12-23
  • 2022-01-11
  • 2021-08-06
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-05
  • 2021-12-01
  • 2021-12-14
  • 2021-12-19
相关资源
相似解决方案