C语言:字符串转换ASCII码值及还原

该文章主要讲使用C语言如何将字符串转换为ACSII码值以及如何进行还原的。

#include 
#include 
#include 
#include 

void printfString(void)
{
	char str[36] = "0x50C6,38063850";
	int i = 0;

	while(str[i] != '\0')
	{
		printf("%02x", str[i]);
		i++;
	}

	printf("\n");
}

uint8_t getValue(uint8_t val)
{
	if(val >= '0' && val <= '9')
	{
		val -= '0';
	}
	else if(val >= 'a' && val <= 'f')
	{
		val = val - 'a' + 0x0a;
	}
	else if(val >= 'A' && val <= 'F')
	{
		val = val - 'A' + 0x0A;
	}

	return val;
}

int main()
{
	//printfString();

	uint8_t buffer[36] = "3078353043362c3338303633383530";    //0x50C6,38063850
	char data = 0;
	uint8_t dataHigh = 0;
	uint8_t dataLow = 0;

	printf("The string context is: ");

	for(int i = 0; i < 32;)
	{
		dataHigh = getValue(buffer[i++]);
		dataLow = getValue(buffer[i++]);
		data = (dataHigh << 4) + dataLow;
		printf("%c", data);
	}

	printf("\n");

	return 0;
}

 程序运行结果:

allen@ubuntu:~/Qt$ ./a.out 
3078353043362c3338303633383530

allen@ubuntu:~/Qt$ ./a.out 
The string context is: 0x50C6,3806385

你可能感兴趣的:(服务器,linux,前端)