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

2011-6-2 13:38 4954 7 7 分类: 软件与OS

要求:将一个以字符串形式存储的十六进制数转换为整数。该字符串前面可有0x或0X前缀(没有也可以)。当碰到非十六进制要求的字符或者碰到了nul字符,则转换结束。

 
/******************************************************************************/
/*
* 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中测试如下:

 

ContractedBlock.gifExpandedBlockStart.gifView 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 }

 

程序运行正常。

PARTNER CONTENT

文章评论0条评论)

登录后参与讨论
EE直播间
更多
我要评论
0
7
关闭 站长推荐上一条 /3 下一条