将16进制字符串转换为16进制数的例程

工作中遇到了该问题,回家参考一篇文章实验了下,是可以的:

/***********************************************************************
@
@ 函数名	: strtohex.c
@ 功能	: 将字符串表示的16进制转化为真正的16进制
@ 作者	: xiangpingli
@ 日期	: 2012-08-28
@
************************************************************************/

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{

	printf("\n------------------------------------------\n");
	char szValue[]= "0x11";
	int 	nValue1 = 0;
	int   nValue2 = 0;

	sscanf(szValue,"%x",&nValue1);
	printf("0x%x\n",nValue1);

	nValue2 = (int)strtol(szValue, NULL, 16);
	printf("0x%x\n",nValue2);


	printf("\n------------------------------------------\n");

	int i = 0;
	char hwid[128] = {0};
	char tmp[8] = {0};
	int   hwidhex[128] = {0};


	strcpy(hwid, "00112233445566778899aabbccddeeff");

	printf("hwid:%s\n", hwid);

	for(i = 0; i < 32; i+=2)
	{
		tmp[0] = '0';
		tmp[1] = 'x';
		tmp[2] = hwid[i];
		tmp[3] = hwid[i+1];
		tmp[4] = '\0';
		printf("tmp:%s\n", tmp);

		hwidhex[i/2] = (int )strtol(tmp, NULL, 16);
		printf("hwidhex[i/2]:%x\n", hwidhex[i/2]);
	}

	printf("\n------------------------------------------\n");

	int hwidhex2[128] = {0};
	printf("hwid:%s\n", hwid);

	for(i = 0; i < 32; i+=2)
	{
		tmp[0] = '0';
		tmp[1] = 'x';
		tmp[2] = hwid[i];
		tmp[3] = hwid[i+1];
		tmp[4] = '\0';
		printf("tmp:%s\n", tmp);

		sscanf(tmp, "%x", &hwidhex2[i/2]);
		printf("hwidhex[i/2]:%x\n", hwidhex2[i/2]);
	}

	return 0;
}

运行结果:

root@xiangpingli:/home/linux/Desktop/samba/exercise/build# ../binary/strtohex 

------------------------------------------
0x11
0x11

------------------------------------------
hwid:00112233445566778899aabbccddeeff
tmp:0x00
hwidhex[i/2]:0
tmp:0x11
hwidhex[i/2]:11
tmp:0x22
hwidhex[i/2]:22
tmp:0x33
hwidhex[i/2]:33
tmp:0x44
hwidhex[i/2]:44
tmp:0x55
hwidhex[i/2]:55
tmp:0x66
hwidhex[i/2]:66
tmp:0x77
hwidhex[i/2]:77
tmp:0x88
hwidhex[i/2]:88
tmp:0x99
hwidhex[i/2]:99
tmp:0xaa
hwidhex[i/2]:aa
tmp:0xbb
hwidhex[i/2]:bb
tmp:0xcc
hwidhex[i/2]:cc
tmp:0xdd
hwidhex[i/2]:dd
tmp:0xee
hwidhex[i/2]:ee
tmp:0xff
hwidhex[i/2]:ff

------------------------------------------
hwid:00112233445566778899aabbccddeeff
tmp:0x00
hwidhex[i/2]:0
tmp:0x11
hwidhex[i/2]:11
tmp:0x22
hwidhex[i/2]:22
tmp:0x33
hwidhex[i/2]:33
tmp:0x44
hwidhex[i/2]:44
tmp:0x55
hwidhex[i/2]:55
tmp:0x66
hwidhex[i/2]:66
tmp:0x77
hwidhex[i/2]:77
tmp:0x88
hwidhex[i/2]:88
tmp:0x99
hwidhex[i/2]:99
tmp:0xaa
hwidhex[i/2]:aa
tmp:0xbb
hwidhex[i/2]:bb
tmp:0xcc
hwidhex[i/2]:cc
tmp:0xdd
hwidhex[i/2]:dd
tmp:0xee
hwidhex[i/2]:ee
tmp:0xff
hwidhex[i/2]:ff

参考文章:

http://blog.csdn.net/ixidof/article/details/6081217


你可能感兴趣的:(工作,null)