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

后端 未结 7 1251
春和景丽
春和景丽 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 06:51

    You'll never convince me that this operation is a performance bottleneck. The efficient way is to make good use of your time by using the standard C library:

    static unsigned char gethex(const char *s, char **endptr) {
      assert(s);
      while (isspace(*s)) s++;
      assert(*s);
      return strtoul(s, endptr, 16);
    }
    
    unsigned char *convert(const char *s, int *length) {
      unsigned char *answer = malloc((strlen(s) + 1) / 3);
      unsigned char *p;
      for (p = answer; *s; p++)
        *p = gethex(s, (char **)&s);
      *length = p - answer;
      return answer;
    }
    

    Compiled and tested. Works on your example.

提交回复
热议问题