user1396367
user1396367

Reputation:

How can I get decimal from string hexdecimal

How can I get decimal from string hexdecimal:
I have unsigned char* hexBuffer = "eb89f0a36e463d";. And I have unsigned char* hex[5] ={'\\','x'};.
I copy from hexBuffer first two char "eb" to hex[2] = 'e'; hex[3] = 'b';.
Now i have string "\xeb" or "\xEB" inside hex.
As we all know 0xEB its ahexdecimal and we can convert to 235 decimal.

How can I convert "\xEB" to 235(int)?

(Thanks to jedwards)
My Answer (maybe it 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++];}  
}

Upvotes: 3

Views: 467

Answers (3)

juanchopanza
juanchopanza

Reputation: 227608

In C++11 you can use one of the string to unsigned integral type and integral conversion functions:

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

Of course, this requires that your string represents a number that can fit into the integer type on the LHS of the expression.

Upvotes: 5

jedwards
jedwards

Reputation: 30250

Typically I see homebrew implementations of hex2dec functions look like:

#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));
}

Which displays:

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

I'll leave it as an exercise for you to go from nibble to byte and then from byte to arbitrary length string.

Note: I only used #include and printf to demonstrate the functionality of the hex2dec_nibble function. Its not necessary to use these.

Upvotes: 3

OmnipotentEntity
OmnipotentEntity

Reputation: 17131

The function you want is called sscanf.

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

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

Upvotes: 8

Related Questions