Convert two ASCII Hexadecimal Characters (Two ASCII bytes) in one byte

后端 未结 6 2387
余生分开走
余生分开走 2020-12-18 13:08

I want to convert two ASCII bytes to one hexadecimal byte. eg.

0x30 0x43 => 0x0C , 0x34 0x46 => 0x4F ...

The ASCII bytes are a number bet

6条回答
  •  情话喂你
    2020-12-18 13:38

    Here's a version that works with both upper and lower-case hex strings:

    void hex_decode(const char *in, size_t len, uint8_t *out)
    {
      unsigned int i, hn, ln;
      char hc, lc;
    
      memset(out, 0, len);
    
      for (i = 0; i < 2*len; i += 2) {
    
        hc = in[i];
        if ('a' <= hc && hc <= 'f') hc = toupper(hc);
        lc = in[i+1];
        if ('a' <= lc && lc <= 'f') lc = toupper(lc);
    
        hn = hc > '9' ? hc - 'A' + 10 : hc - '0';
        ln = lc > '9' ? lc - 'A' + 10 : lc - '0';
    
        out[i >> 1] = (hn << 4 ) | ln;
      }
    }
    

提交回复
热议问题