且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何正确地转换为十六进制字符串字节数组用C?

更新时间:2023-11-15 19:49:40

您可以使用与strtol()代替。

只需更换这行:

 的sscanf(POS,%2hhx,&安培; VAL [计数]);

 字符BUF [10];
sprintf的(BUF,0X%C%C,POS [0],POS [1]);
VAL [计数] =与strtol(BUF,NULL,0);

更新:你能避免使用的sprintf()使用这段代码来代替:

 字符BUF [5] = {0,X,POS [0],POS [1],0};
VAL [计数] =与strtol(BUF,NULL,0);

I need to convert a string, containing hex values as characters, into a byte array. Although this has been answered already here as the first answer, I get the following error:

warning: ISO C90 does not support the ‘hh’ gnu_scanf length modifier [-Wformat]

Since I do not like warnings, and the omission of hh just creates another warning

warning: format ‘%x’ expects argument of type ‘unsigned int *’, but argument 3 has type ‘unsigned char *’ [-Wformat]

my question is: How to do this right? For completion, I post the example code here again:

#include <stdio.h>

int main(int argc, char **argv)
{
    const char hexstring[] = "deadbeef10203040b00b1e50", *pos = hexstring;
    unsigned char val[12];
    size_t count = 0;

     /* WARNING: no sanitization or error-checking whatsoever */
    for(count = 0; count < sizeof(val)/sizeof(val[0]); count++) {
        sscanf(pos, "%2hhx", &val[count]);
        pos += 2 * sizeof(char);
    }

    printf("0x");
    for(count = 0; count < sizeof(val)/sizeof(val[0]); count++)
        printf("%02x", val[count]);
    printf("\n");

    return(0);
}

You can use strtol() instead.

Simply replace this line:

sscanf(pos, "%2hhx", &val[count]);

with:

char buf[10];
sprintf(buf, "0x%c%c", pos[0], pos[1]);
val[count] = strtol(buf, NULL, 0);

UPDATE: You can avoid using sprintf() using this snippet instead:

char buf[5] = {"0", "x", pos[0], pos[1], 0};
val[count] = strtol(buf, NULL, 0);