簡體   English   中英

如何在C中將十六進制轉換為字節數組

[英]How to convert a hexadecimal to byte array in C

在“ C”中是否有可用的庫將C中的十六進制轉換為字節數組

例如

Input const char *ptr="ff:ff:fe:ff"

有一個“:”分隔符值

您可以使用strtoll函數進行單個字節的轉換。 該函數將base參數作為第三個參數,並報告輸入中的新位置,讓您決定是跳過定界符還是讀取更多數據,或者完成循環:

char *ptr="ff:ff:fe:ff";
for (;;) {
    int res = strtol(ptr, &ptr, 16);
    printf("%x\n", res);
    if (*ptr == ':') {
        ptr++;
    } else {
        break;
    }
}

ideone演示

您可能可以使用sscanf()讀取值。

#include <stdio.h>

int main() {
    const char *input = "ff:ff:fe:ff";
    unsigned int array[4];
    int ret;

    ret = sscanf(input, "%02x:%02x:%02x:%02x",
        &array[0], &array[1], &array[2], &array[3]);

    if (ret != 4) {
        printf("Match failed.\n");
        return -1;
    }

    printf("array = { %02x, %02x, %02x, %02x }\n",
        array[0], array[1], array[2], array[3]);

    return 0;
}

輸出:

array = { ff, ff, fe, ff }
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define h2i(x) (isdigit(x) ? (x) - '0' : tolower(x) - 'a' + 10)

int main(void){
    const char *ptr="ff:ff:fe:ff";
    size_t size = (strlen(ptr)+1)/3;
    unsigned char byte[size];
    int i;
    for(i = 0; i < size; ++i){
        byte[i] = h2i(ptr[i*3])*16 + h2i(ptr[i*3+1]);
        //printf("%02x", byte[i]);//for check
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM