ASCII字符串转换成16进制

本文详细介绍了如何将网络接收的MAC地址(ASCII格式)转换为6个字节的二进制数的过程,包括算法实现和代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近遇到一个小问题,从网络接收到的包中含有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]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值