C语言字符数组与16进制互相转换

##需求

在机顶盒上做一个CA WIFI喂卡的功能,

##设计

流程比较简单:

  • 子卡(的机器)发送申请

  • 母卡(的机器)接受申请,并且审核,如果同意的话则从母卡中读取数据,发送给子卡机器

  • 子卡(的机器)确认母卡消息,如果母卡同意,则将数据写入子卡,如果不同意则在盒子上显示

  • 子卡(的机器)最后喂卡是否成功,需要反馈给母卡,母卡做出相应的界面显示

##实现

整个流程建立Socket通信完成,这里Socket的通信是由上层完成,也就是Android层盒子两端相互交互,读卡和写卡则从底层接口中获取,其中读取出来的数据非正常的字符串,排除非法字符的问题,这里转换成16进制的字符串以及附带长度传输。

母卡读卡数据的接口如下,从母卡中读取数据,并且转换为16进制

void read_mother_feeddata()
{
	int datalength = 0;
	int ret = 0;
	int i,j;
	char feedData[128] = {0};
    char feeddataHex[256] = {0};
	ret = ReadFeedDataFromMother(feedData,&datalength);
	if(ret == 1)   // read feed data success
	{
		for(i = 0,j = 0 ; i < datalength;i++,j += 2)   // char to hex 
		{
			sprintf((char *) feeddataHex + j,"%02x",feedData[i]);
		}
		// return feeddataHex and datalength to application ,and Socket tranfrom this data on Android
		....
	}
	
    return;
}

子卡写入数据接口,将母卡的16进制数据准换成字符数组,写入子卡,因为母卡转化那边英文字母都是小写,就没有做大写的转换

void write_feeddata_to_son()
{
	char motherfeeddataHex[256] = {0};
	char motherfeeddata[128] = {0};

	int ret = 0;
	int datalength;
	int i;

	char u8Temp;

	// get motherfeeddataHex and datalength
	for(i = 0; i < datalength;i++)
	{
		if (motherfeeddataHex[i * 2] >= 0x30 && motherfeeddataHex[i * 2] <= 0x39)
		{
			// high 4 bit  1 ~ 9
			u8Temp = motherfeeddataHex[i * 2] - 0x30;
			motherfeeddata[i] = (u8Temp & 0x0F)<<4;
		}
		else if (motherfeeddataHex[i * 2] >= 0x61 && motherfeeddataHex[i * 2] <= 0x7a)
		{
			// high 4 bit  a ~ z
			u8Temp = motherfeeddataHex[i * 2] - 0x61 + 10;
			motherfeeddata[i] = (u8Temp & 0x0F)<<4;
		}
		if (motherfeeddataHex[i * 2 + 1] >= 0x30 && motherfeeddataHex[i * 2 + 1] <= 0x39)
		{
			// low 4 bit  1 ~ 9
			u8Temp = motherfeeddataHex[i * 2 + 1] - 0x30;
			motherfeeddata[i] |= u8Temp & 0x0F;
		}
		else if (motherfeeddataHex[i * 2 + 1] >= 0x61 && motherfeeddataHex[i * 2] <= 0x7a)
		{
			// low 4 bit  a ~ z
			u8Temp = motherfeeddataHex[i * 2 + 1] - 0x61 + 10;
			motherfeeddata[i] |= u8Temp & 0x0F;
		}

	}
	ret = WriteFeedDataToSon(motherfeeddata,datalength);
	if(ret == 1)   // read feed data success
	{
		// return application result,and and Socket tranfrom the result on Android
		...
	}
}

Socket 通信由Java代码完成,做过很多次这种Socket交互,沿用之前那套就比较简单了,只是做好插拔卡回调开启和关闭Socket就行

你可能感兴趣的:(C)