HEX/BCD/BYTE/之间的转换

/*********************************
HEX/BCD/BYTE/之间的转换
**********************************/
/*
将srcBuff指向的len个字节的数据,按十六进制字符编码转换,并存于tarBuff中
*/
void ByteToHexStr(char *tarBuff, const unsigned char *srcBuff, unsigned int len)
{
	char byte;
	
	while (len--) 
	{
		byte = *srcBuff >> 4;
		*tarBuff++ = (byte>9) ? (byte+'A'-10) : (byte+'0');
		
		byte = *srcBuff & 0x0F;
		*tarBuff++ = (byte>9) ? (byte+'A'-10) : (byte+'0');
		
		++srcBuff;
	}
	*tarBuff = 0;//空字符
}

/*
将无符号字符数据,转换为十六进制数据,并存于tarBuff中
*/
void BytetoBCD(unsigned char *tarBuff, const unsigned char *srcBuff, unsigned short len)
{
	while (len--) {
		*tarBuff++ = (((*srcBuff / 10) % 10) << 4) | (*srcBuff % 10);
		++srcBuff;
	}
}
/*
将srcBuff指向的len个长度的字符串数据,按十六进制字符编码转换为字符,并存于tarBuff中
*/
void HexStrToByte(unsigned char *tarBuff, const char *srcBuff, unsigned int len)
{
	char byte;
	
	if (len % 2 == 1)
		--len;
	
	while (len) {
		byte = *srcBuff>'9' ? (*srcBuff-'A'+10) : (*srcBuff-'0');
		++srcBuff;
		byte <<= 4;
		
		byte |= *srcBuff>'9' ? (*srcBuff-'A'+10) : (*srcBuff-'0');
		++srcBuff;
		
		*tarBuff++ = byte;
		len -= 2;
	}
}


#include 

int main(int argc, char *argv[])
{
	int i=0,j=0;
	const char TestStr1[] = "12345ABCDE";
	const unsigned char TestStr2[] = {1,2,3,4,5,10,11,12,13,14};
	char mystr[10] = "";
	unsigned char mystr1[10] = {0};
	unsigned char mystr2[10] = {0};
	
	printf("TestStr1:%s\n",TestStr1);
	printf("TestStr2:%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
	TestStr2[0],TestStr2[1],TestStr2[2],TestStr2[3],TestStr2[4],TestStr2[5],
	TestStr2[6],TestStr2[7],TestStr2[8],TestStr2[9]);
	
	ByteToHexStr(mystr, TestStr2, 10);
	printf("ByteToHexStr:%s\n",mystr);
	
	BytetoBCD(mystr1, TestStr2, 10);
	for (i=0;i<10;i++)
	{
		printf("mystr1[%d]:%02x",i,mystr1[i]);
		if (i==9)
		printf("\r\n");
	}
	
	HexStrToByte(mystr2, TestStr1, 10);
	for (j=0;j<10;j++)
	{
		printf("mystr2[%d]:%02x",j,mystr2[j]);
		if (i==9)
		printf("\r\n");
	}
}

你可能感兴趣的:(C/C++)