How can I get a decimal value from a hexdecimal string

How can I get the decimal value from the hexdecimal string:
I unsigned char* hexBuffer = "eb89f0a36e463d";. And I have unsigned char* hex[5] ={'\\','x'};.
I will copy from the hexBufferfirst two char "eb"'s hex[2] = 'e'; hex[3] = 'b';.
Now I have a line "\xeb"or "\xeb"inside hex.
As we all know, 0xEBits axxdecimal, and we can convert to 235decimal.

How to convert "\xeb"to 235(int)?

(Thanks to jedwards )
My answer (maybe this will be useful for someone):

/*only for lower case & digits*/ 
unsigned char hash[57] ="e1b026972ba2c787780a243e0a80ec8299e14d9d92b3ce24358b1f04";  
unsigned char chr =0;  
int dec[28] ={0}; int i = 0;int c =0;  
while( *hash )  
{  
c++;  
(*hash >= 0x30 && *hash <= 0x39) ? ( chr = *hash - 0x30) : ( chr = *hash - 0x61 + 10);  
*hash++;  
if ( c == 1) dec[i] = chr * 16; else{ dec[i] += chr; c = 0; dec[i++];}  
}
+3
source share
3 answers

Usually I see that the homebrew implementation of the hex2dec functions is as follows:

#include <stdio.h>

unsigned char hex2dec_nibble(unsigned char n)
{
    // Numbers
    if(n >= 0x30 && n <= 0x39)
    {
        return (n-0x30);
    }
    // Upper case
    else if(n >= 0x41 && n <= 0x46)
    {
        return (n-0x41+10);
    }
    // Lower case
    else if(n >= 0x61 && n <= 0x66)
    {
        return (n-0x61+10);
    }
    else
    {
        return -1;
    }    
}


int main()
{   
    unsigned char t;
    t = '0';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'A';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'F';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'G';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'a';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'f';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = 'g';  printf("%c = %d\n", t, hex2dec_nibble(t));
    t = '=';  printf("%c = %d\n", t, hex2dec_nibble(t));
}

What is displayed:

0 = 0
A = 10
F = 15
G = 255
a = 10
f = 15
g = 255
= = 255

, .

. #include printf, hex2dec_nibble. .

+4

, , sscanf.

http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/

int integer;
sscanf(hexBuffer, "%x", &integer);
+8

++ 11 :

long i = std::stol("ff", nullptr, 16); // convert base 16 string. Accepts 0x prefix.

, , , LHS .

+5

All Articles