How to turn a hex string into an unsigned char array?

后端 未结 7 1246
春和景丽
春和景丽 2020-11-27 06:05

For example, I have a cstring \"E8 48 D8 FF FF 8B 0D\" (including spaces) which needs to be converted into the equivalent unsigned char array {0xE8,0x48,0

相关标签:
7条回答
  • 2020-11-27 07:08

    For a pure C implementation I think you can persuade sscanf(3) to do what you what. I believe this should be portable (including the slightly dodgy type coercion to appease the compiler) so long as your input string is only ever going to contain two-character hex values.

    #include <stdio.h>
    #include <stdlib.h>
    
    
    char hex[] = "E8 48 D8 FF FF 8B 0D";
    char *p;
    int cnt = (strlen(hex) + 1) / 3; // Whether or not there's a trailing space
    unsigned char *result = (unsigned char *)malloc(cnt), *r;
    unsigned char c;
    
    for (p = hex, r = result; *p; p += 3) {
        if (sscanf(p, "%02X", (unsigned int *)&c) != 1) {
            break; // Didn't parse as expected
        }
        *r++ = c;
    }
    
    0 讨论(0)
提交回复
热议问题