C++ middle hexadecimal string to a number

  • 2020-05-27 06:50:03
  • OfStack

C++ 106 base string to number (numeric)

There are two main methods, both of which are the use of existing functions:

Method 1: sscanf ()

Function name: sscanf
Power: formats input from a string
int sscanf(char *string, char *format[,argument...] );

The above format is %. x is to format a string as a hexadecimal number


#include <stdio.h>  
void main()  
  char* p = "0x1a";   
  int nValude = 0;     
  sscanf(p, "%x", &nValude);   
  printf("%d\r\n", nValude); 



Method 2: strtol ()

Function name: strtol
Power: converts a string to a long integer
Usage: long strtol(char *str, char **endptr, int base);

So base up here is what we're going to convert to


#include <stdio.h>  
#include <stdlib.h>  
void main()  
  char* p = "0x1b";   
  char* str;   
  long i = strtol(p, &str, 16);
  printf("%d\r\n", i);



In fact, there is another method, which is to use a string array initialized to 0~9~a~f, that is, a table of 106 corresponding table, which can be used to calculate the value of a string of 106 hexadecimal, but this is too much trouble and is not recommended.

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!

Related articles: