鹰之歌

既然你崇拜鹰,就要像鹰一样翱翔天际,俯瞰大地。哪怕会摔的粉身碎骨。

导航

将字符串存储形式的十六进制数转换为整数

/******************************************************************************/
/*
* 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 }

运行结果符合要求。

posted on 2011-06-02 13:30  鹰之歌  阅读(342)  评论(0编辑  收藏  举报