unsigned char 与 十六进制char 互转

 java没有无符号字符串, 让他们转成16进制字符串后再传进来, 我们转成unsigned char 后我们再用;这是我用到的方法

//十六进制char 转 unsigned char
int hexstr_to_byte(const   char   *   pInHexString,int   nInLen,unsigned char   *   pOut,int   *   nOutLen)
{
	if(pInHexString==NULL   ||   pOut==NULL   ||   (nInLen%2))
	{
        return   -1;
	}
	int   nIndex=0;
    unsigned char   nData=0;
    unsigned char   nOut=0;
    char   Temp[2];

    for(int   i=0;i <nInLen;i   +=   2)
    {
        Temp[0]=pInHexString[i];
        Temp[1]=pInHexString[i+1];

        for(int   j=0;j <2;++j)
        {
            switch(Temp[j])
            {
            case   '0':
            case   '1':
            case   '2':
            case   '3':
            case   '4':
            case   '5':
            case   '6':
            case   '7':
            case   '8':
            case   '9':
                nData=Temp[j]- '0';
                nOut   +=nData <<   ((1-j)*4);
                break;
            case   'A':
            case   'B':
            case   'C':
            case   'D':
            case   'E':
            case   'F':
                nData=Temp[j]- 'A'   +   10;
                nOut   +=nData <<   ((1-j)*4);
                break;
            case   'a':
            case   'b':
            case   'c':
            case   'd':
            case   'e':
            case   'f':
                nData=Temp[j]- 'a'   +   10;
                nOut   +=nData <<   ((1-j)*4);
                break;
            default:
                return   -1;
            }
        }
        pOut[nIndex++]=nOut;
        nOut=0;
    }
	*nOutLen=nIndex;
	return   0;
}
//unsigned char 转 十六进制字符串
void byte_to_hexstr( const unsigned char* source, char* dest, int sourceLen )
{
	short i;
	unsigned char highByte, lowByte;

	for (i = 0; i < sourceLen; i++)
	{
		highByte = source[i] >> 4;
		lowByte = source[i] & 0x0f ;

		highByte += 0x30;

		if (highByte > 0x39)
			dest[i * 2] = highByte + 0x07;
		else
			dest[i * 2] = highByte;

		lowByte += 0x30;
		if (lowByte > 0x39)
			dest[i * 2 + 1] = lowByte + 0x07;
		else
			dest[i * 2 + 1] = lowByte;
	}
	return ;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值