C语言 字符串和16进制数的互相转化

16进制到字符串:

#include 
#include 
#include 
int main()
{
	int a[6] = {0x12,0x34,0x56,0x78,0xab,0xcd};
	char *str = (char*)malloc(32);
	memset(str,0,32);
	int i = 0;
	for(i = 0; i < 6;i++)
	{
		sprintf(str,"%s%x",str,a[i]);
	}
	for(i = 0; i < strlen(str);i++)
	{
		printf("%c ",str[i]);
	}
	printf("\n%s\n",str);
	return 0;
}
	

字符串到16进制:

#include 
#include 
#include 

int main()
{
	/*char *str = (char *)malloc(6);
	sprintf(str,"123456");*/
	char *str = "123456";
	int tmp;
	int a[6]={0};
	int i=0;
	printf("%ld\n",strlen(str));
	for(i = 0; i< 6; i++)
	{
		sscanf(str,"%1x",&a[i]);
		printf("a[%d] = %2x \n",i,a[i]);
		str++;
	}
	for(i = 0;i < 6;i++)
	{
		printf("a[%d] = %d \n",i,a[i]);
	}
	
	return 0;
}

 

你可能感兴趣的:(LinuxC)