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

后端 未结 6 2358
余生分开走
余生分开走 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:32

    You can use strtol(), which is part of avr-libc, or you can write just your specific case pretty easily:

    unsigned char charToHexDigit(char c)
    {
      if (c >= 'A')
        return c - 'A' + 10;
      else
        return c - '0';
    }
    
    unsigned char stringToByte(char c[2])
    {
      return charToHexDigit(c[0]) * 16 + charToHexDigit(c[1]);
    }
    

提交回复
热议问题