16進位制字串轉位元組

大碼猴k發表於2020-12-22

16進位制字串轉位元組

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void hex_str_to_byte(char *in, int len, unsigned char *out)
{
    char *str = (char *)malloc(len);
    memset(str, 0, len);
    memcpy(str, in, len);
    for (int i = 0; i < len; i += 2)
    {
        //小寫轉大寫
        if (str[i] >= 'a' && str[i] <= 'f')
            str[i] = str[i] - 0x20;
        if (str[i + 1] >= 'a' && str[i] <= 'f')
            str[i + 1] = str[i + 1] - 0x20;
        //處理第前4位
        if (str[i] >= 'A' && str[i] <= 'F')
            out[i / 2] = (str[i] - 'A' + 10) << 4;
        else
            out[i / 2] = (str[i] & ~0x30) << 4;
        //處理後4位, 並組合起來
        if (str[i + 1] >= 'A' && str[i + 1] <= 'F')
            out[i / 2] |= (str[i + 1] - 'A' + 10);
        else
            out[i / 2] |= (str[i + 1] & ~0x30);
    }
    free(str);
}

int main()
{
    char *str = "FF32333435363738393a3b3c3d3e3f40";
    unsigned char temp[16] = {0};
    hex_str_to_byte(str, strlen("ff32333435363738393a3b3c3d3e3f40"), temp);
    for (int i = 0; i < 16; i++)
    {
        printf("%02x ", temp[i]);
    }
    printf("\n");
    return 0;
}

演示

在這裡插入圖片描述

相關文章