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 2022-11-15 16:40  林西索  阅读(797)  评论(0编辑  收藏  举报