簡體   English   中英

在C中將字符串轉換為十六進制整數

[英]convert a string to hex integer in C

我有以下C字符串

"72e4247d3c91f424c62d909d7c1553a5"

它由32個十六進制數字組成。 它是一個包含4個十進制整數的數組。 如何從這個數組中取回整數形式的數字?

您必須分別解析四個32位/ 8個十六進制數字塊。 最簡單的方法是

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

void parse_hex4(char const *str, uint32_t num[4])
{
    char buf[9];  // 8 hex digits + NUL

    buf[8] = '\0';
    for (int i=0; i<4; i++) {
        memcpy(buf, str + i * 8, 8);
        num[i] = strtoul(buf, NULL, 16);
    }
}

這假設str是零填充的,正好是32個字符長,並且沒有輸入驗證。 如果你使用的是Redmond的編譯器,那就是1980年 ,那就使用unsigned long而不是uint32_t

你試過strtol嗎?

int val = (int) strtol (hex_string, NULL, 16);

如果它是一個扁平數組,則重復子串。

問候

暫無
暫無

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

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