A method to represent a number in the form of a hexadecimal string as a number

For example, for a number, the hexadecimal representation is 0xC5, the decimal size is 197, and the hexadecimal string form is "C5". Now how to convert "C5" to 197?

First "C5" consists of two characters: 'C' and '5'. 'C' is the hexadecimal representation of the upper 4 bits, the size of the decimal system is 12, and the binary value is: 1100. '5' is the hexadecimal representation of the lower 4 bits, the size of the decimal system is 5, and the binary value is: 0101. The high 4 bits are shifted to the left by 4 bits, and the low 4 bits are added to get the number: 1100 0101, which is the number 197.

So what we have to do is to convert the characters 'C' and '5' into decimal numbers, then shift the decimal number of 'C' to the left by 4 bits, and then add it to the decimal number of '5' to get the number type of "C5".

First write a function that can convert the 16 hexadecimal characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F into numbers:

byte char_to_hex(char chr)
{
  if ((chr >= '0') && (chr <= '9'))
  {
    return chr - '0';
  }
  if ((chr >= 'A') && (chr <= 'F'))
  {
    return chr - 'A' + 10;
  }
  if ((chr >= 'a') && (chr <= 'f'))
  {
    return chr - 'a' + 10;
  }
  return -1;
}
<

Guess you like

Origin blog.csdn.net/wjz110201/article/details/131529924