随笔 - 100  文章 - 0  评论 - 6  阅读 - 88682

C++---16进制的字符串转16进制数

转:https://blog.csdn.net/Mmagic1/article/details/111413079

复制代码
#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;
}

//#define CHARSIZE 3 几个字符转为一个16进制
#define CHARSIZE 2
int hex2bytes(const char* hex, char* bytes, int size)
{
    int len = strlen(hex);
    int nbytes = (len + 1) / CHARSIZE;
    if (nbytes > size)
    {
        return -1;
    }

    int n = 0;
    for (n = 0; n != nbytes; ++n)
    {
        int lndx = n * CHARSIZE;
        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[])
{//07 0A 02 10 03 00 00 00 00 00
    const char* hex = "48656c6c6f20576f726c6400";//Hello World
    char stream[12];
    int nbytes = hex2bytes(hex, stream, sizeof(stream));
    if (nbytes != -1)
    {
        int i = 0;
        for (; i < nbytes; ++i)
        {
            printf("%02x ", stream[i]);
        }

        printf("\n");
        for (i = 0; i < nbytes; ++i)
        {
            printf("%c", stream[i]);
        }
    }

    return 0;
}
复制代码

 

posted on   林西索  阅读(1178)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示