簡體   English   中英

C庫函數,用於將十六進制數字字符串轉換為整數嗎?

[英]C Library function for converting a string of hex digits to ints?

我有一個可變長度的字符串,其中每個字符代表一個十六進制數字。 我可以遍歷字符並使用case語句將其轉換為十六進制,但是我覺得必須有一個標准的庫函數來處理這個問題。 有這樣的事嗎?

我想做的事的例子。 "17bf59c" -> int intarray[7] = { 1, 7, 0xb, 0xf, 5, 9, 0xc}

不,沒有這樣的功能,可能是因為(現在我猜,我不是很長時間的C標准庫設計師),這很容易與現有功能組合在一起。 這是一種體面的方式:

int * string_to_int_array(const char *string, size_t length)
{
  int *out = malloc(length * sizeof *out);
  if(out != NULL)
  {
    size_t i;
    for(i = 0; i < length; i++)
    {
      const char here = tolower(string[i]);
      out[i] = (here <= '9') ? (here - '\0') : (10 + (here - 'a'));
    }
  }
  return out;
}

注意:以上未經測試。

還要注意一些可能不明顯但仍然很重要的事情(在我看來):

  1. const用於該函數視為“只讀”的指針參數。
  2. 不要重復out指向的類型,請使用sizeof *out
  3. 不要在C中malloc()的返回值。
  4. 在使用內存之前,請檢查malloc()成功。
  5. 不要硬編碼ASCII值,請使用字符常量。
  6. 上面仍然假設編碼是'a'..'f'連續的,並且可能會在EBCDIC上中斷。 您有時會得到所要支付的費用。 :)

使用strtol

void to_int_array (int *dst, const char *hexs)
{
    char buf[2] = {0};
    char c;
    while ((c = *hexs++)) {
        buf[0] = c;
        *dst++ = strtol(buf,NULL,16);
    }
}

這是另一個允許您傳遞輸出數組的版本。 大多數時候,您不需要malloc,這很昂貴。 堆棧變量通常很好,並且您知道輸出永遠不會比輸入大。 如果太大,仍然可以傳遞分配的數組,或者需要將其備份。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

/* str of length len is parsed to individual ints into output
* length of output needs to be at least len.
* returns number of parsed elements. Maybe shorter if there
* are invalid characters in str.
*/
int string_to_array(const char *str, int *output)
{
    int *out = output;
    for (; *str; str++) {
        if (isxdigit(*str & 0xff)) {
            char ch = tolower(*str & 0xff);
            *out++ = (ch >= 'a' && ch <= 'z') ? ch - 'a' + 10 : ch - '0';
        }
    }
    return out - output;
}

int main(void)
{
    int values[10];
    int len = string_to_array("17bzzf59c", values);
    int i = 0;
    for (i = 0; i < len; i++) 
        printf("%x ", values[i]);
    printf("\n");
    return EXIT_SUCCESS;
}
#include <stdio.h>

int main(){
    char data[] =  "17bf59c";
    const int len = sizeof(data)/sizeof(char)-1;
    int i,value[sizeof(data)/sizeof(char)-1];

    for(i=0;i<len;++i)
        sscanf(data+i, "%1x",value + i);

    for(i=0;i<len;++i)
        printf("0x%x\n", value[i]);
    return 0;
}

暫無
暫無

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

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