C++ example of converting a hexadecimal string to an int plastic value

  • 2020-06-12 10:14:19
  • OfStack

Base 106 (hex or subscript 16) is a kind of carry system in mathematics for every hexadecimal 1. 1 is generally represented by the Numbers 0 to 9 and the letters A to F (or a~f), where A~F represents 10 to 15, and these are called base 106 Numbers.

In the development, it is often necessary to convert hexadecimal string into plastic. I have written a code for your reference:


#include <stdio.h>
#include <string.h>
// Character conversion to plastic 
int hex2int(char c)
{
 if ((c >= 'A') && (c <= 'Z'))
 {
 return c - 'A' + 10;
 }
 else if ((c >= 'a') && (c <= 'z'))
 {
 return c - 'a' + 10;
 }
 else if ((c >= '0') && (c <= '9'))
 {
 return c - '0';
 }
}
int main()
{
 //106 Converts a base string to an int 
 const char* hexStr = "EFA0";
 int data[32] = {0};
 int count = 0;
 for (int i=0; i<strlen(hexStr); i+=2)
 {
 int high = hex2int(hexStr[i]);  // high 4 position 
 int low = hex2int(hexStr[i+1]); // low 4 position 
 data[count++] = (high<<4) + low;
 }
 // A printout 
 for (int i=0; i<strlen(hexStr)/2; i++)
 {
 printf("%d ", data[i]);
 }
 return 1;
}

conclusion


Related articles: