[英]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;
}
注意:以上未經測試。
還要注意一些可能不明顯但仍然很重要的事情(在我看來):
const
用於該函數視為“只讀”的指針參數。 out
指向的類型,請使用sizeof *out
。 malloc()
的返回值。 malloc()
成功。 使用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.