C++字符串转16进制

在串口通讯中,时常涉及到16进制字符串发送,需要将字符串转为16进制。 

Example:string str = "07 0a 02 10 03 00 00 00 00 00"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int char2bits(char ch)
{
    int bits = 0;
    if (ch >= 'a' && ch <= 'z') 
    {
        bits = ch - 'a' + 10;
    } 
    else if (ch >= 'A' && ch <= 'Z') 
    {
        bits = ch - 'A' + 10;
    } 
    else if (ch >= '0' && ch <= '9') 
    {
        bits = ch - '0';
    } 
    else
    {
        bits = -1;
    }
    return bits;
}

int hex2bytes(const char *hex, char *bytes, int size) 
{
    int len = strlen(hex);
    int nbytes = (len + 1) / 3;
    if (nbytes > size) 
    {
        return -1;
    } 

    int n;
    for (n = 0; n != nbytes; ++ n) 
    {
        int lndx = n * 3;
        int rndx = lndx + 1;
        int lbits = char2bits(hex[lndx]);
        int rbits = char2bits(hex[rndx]);
        if (lbits == -1 || rbits == -1)
        {
            return -1;
        }
        bytes[n] = (lbits << 4) | rbits;
    }

    return nbytes;
}

int main(int argc, char* const argv[]) 
{
    const char *hex = "07 0A 02 10 03 00 00 00 00 00";
    char stream[10];
    int nbytes = hex2bytes(hex, stream, 10);
    if (nbytes != -1) 
    {
        int i = 0;
        for ( ; i < nbytes; ++ i) 
        {
            printf("%02x ", stream[i]);
        }
    }
    
    return 0;
}

 

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值