[英]Convert a long hex string in to int array with sscanf
我有一個輸入像
char *input="00112233FFAA";
uint8_t output[6];
使用sscanf
將input
轉換為output
的最簡單方法是什么? (最好是沒有循環的 1 行)我想到的解決方案不會擴展到 20+ 十六進制字符串。
sscanf(input, "%x%x%x%x%x",output[0], output[1]....output[5]);
為什么scanf
如果這可以很容易手寫:
const size_t numdigits = strlen(input) / 2;
uint8_t * const output = malloc(numdigits);
for (size_t i = 0; i != numdigits; ++i)
{
output[i] = 16 * toInt(input[2*i]) + toInt(intput[2*i+1]);
}
unsigned int toInt(char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'F') return 10 + c - 'A';
if (c >= 'a' && c <= 'f') return 10 + c - 'a';
return -1;
}
如果您不想使用循環,那么您需要顯式寫出所有六個(或二十個)數組位置(盡管%x
不是正確的轉換字符 - 它期望指向unsigned int
作為其對應的參數)。 如果你不想全部寫出來,那么你需要使用一個循環 - 它可以很簡單,但是:
for (i = 0; i < 6; i++)
sscanf(&input[i * 2], "%2hhx", &output[i]);
這是一個替代實現。
#include <stdio.h>
#include <stdint.h>
#define _base(x) ((x >= '0' && x <= '9') ? '0' : \
(x >= 'a' && x <= 'f') ? 'a' - 10 : \
(x >= 'A' && x <= 'F') ? 'A' - 10 : \
'\255')
#define HEXOF(x) (x - _base(x))
int main() {
char input[] = "00112233FFAA";
char *p;
uint8_t *output;
if (!(sizeof(input) & 1)) { /* even digits + \0 */
fprintf(stderr,
"Cannot have odd number of characters in input: %d\n",
sizeof(input));
return -1;
}
output = malloc(sizeof(input) >> 1);
for (p = input; p && *p; p+=2 ) {
output[(p - input) >> 1] =
((HEXOF(*p)) << 4) + HEXOF(*(p+1));
}
return 0;
}
@caf 已經有了一個很好的簡單想法。
但是我不得不使用 %02x,現在它工作正常:
for (i = 0; i < 6; i++)
sscanf(&input[i * 2], "%02x", &output[i]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.