ASCII字符串转换成16进制

来源:互联网 发布:淘宝加盟1880是真的吗 编辑:程序博客网 时间:2024/06/06 00:30

最近遇到一个小问题,从网络接收到的包中含有MAC地址(ASCII字符格式,例如”74-29-AF-F2-30-D3”,共18个字符),按照约定我需要把它转换成6个字节的二进制数(74 29 AF F2 30 D3)。
收到的字符串“74-29-AF-F2-30-D3”,是ASCII编码的,内存中就是:37 34 2d 32 39 2d 41 46 2d 46 32 2d 33 30 2d 44 33(共18个字节),现在我要做的就是写一个函数把这个输入转换成6个字节的输出“74 29 AF F2 30 D3”.

思路就是把输入串中的相邻两个字符,变成输出中的一个字节(8bit)的高4bit和低4bit;以前两个字符为例,即把37->7,34->4,组成十六进制的0x74。代码如下(简化后的版本),注意要用到无符号类型,大体思路如下:

void ToHexString(){    unsigned char tmp[]="74-29-AF-F2-30-D3";    unsigned char MacinBinary[6] = {0};    int nMacBinIndex = 0;    int nSrcNumforOneMac = 0;    unsigned char nSrcByteValue = 0;    unsigned char ntempMacByte = 0;    for(int nSrcIndex=0; *(tmp+nSrcIndex)!='\0'; ++nSrcIndex)    {        if(*(tmp+nSrcIndex)!='-')        {            if(*(tmp+nSrcIndex)>='0' && *(tmp+nSrcIndex)<='9')                nSrcByteValue = *(tmp+nSrcIndex) - '0';            if(*(tmp+nSrcIndex)>='A' && *(tmp+nSrcIndex)<='F')                nSrcByteValue = *(tmp+nSrcIndex) - 'A' + 10;            if(*(tmp+nSrcIndex)>='a' && *(tmp+nSrcIndex)<='f')                nSrcByteValue = *(tmp+nSrcIndex) - 'a' + 10;            //got the first half of one MAC byte            if(nSrcNumforOneMac==0)            {                ++nSrcNumforOneMac;                 ntempMacByte = nSrcByteValue << 4;            }            else//the second half of one MAC byte            {                ntempMacByte |= nSrcByteValue;                *(MacinBinary+nMacBinIndex) = ntempMacByte;                ntempMacByte = 0;                nMacBinIndex++;                nSrcNumforOneMac = 0;            }        }    }    printf("\n%2x %2x %2x %2x %2x %2x\n",MacinBinary[0],MacinBinary[1],MacinBinary[2],MacinBinary[3],MacinBinary[4],MacinBinary[5]);}
0 0
原创粉丝点击