0

The conversion i wrote of hexadecimal to decimal number is not working. I am not sure what part is wrong. Do i have to do -7 or something else.

int hex_to_dec(char hexnumber[])
{

int decimal = 0; //integer for the final decimal number
    int bit; //integer representing numbers between 0-9 and letter a-f in hex number
    //a char array containing the input hex number

    int i=0,j=0;

    //the integer i takes the length of the input array
    i =strlen(hexnumber);

    //while there is a next bit in the array
    while(i!=0)
    {
    bit = hexnumber[j];

    //if the bit is a digit do the following
    if(('0' <= bit && bit <= '9'))
    {
    decimal = decimal * 16;
    decimal = decimal + (bit - '0');
    }

    //if the bit is a letter do the following
    if(('a' <= bit && bit <= 'z'))
    {
    decimal = decimal * 16;
    decimal = decimal + (bit - '7');
    }

    i--;
    j++;

    }
 if(('a' <= bit && bit <= 'z'))
    {
    decimal = decimal * 16;
    decimal = decimal + (bit - '7');
    }
   cout<<decimal;
    return decimal;
}

The above is my code for the same.

Andrew-Dufresne
  • 5,464
  • 7
  • 46
  • 68

2 Answers2

2

Instead of

decimal = decimal + (bit - '7');

Try:

decimal = decimal + (bit - 'a' + 10);

This is because a bit value 'a' in base 16 means a decimal value of 10 in base 10.

Also, you should remove this extra statement outside your while loop.

if(('a' <= bit && bit <= 'z'))
    {
    decimal = decimal * 16;
    decimal = decimal + (bit - '7');
    }

To accommodate capital letters, simply add another if condition in your while loop.

if(('A' <= bit && bit <= 'Z'))
    {
    decimal = decimal * 16;
    decimal = decimal + (bit - 'A' + 10);
    }
Abhishek Bansal
  • 12,589
  • 4
  • 31
  • 46
1
int hex2dec(char  hexnumber[])
{
    // get rid of ancient C code (should take a string in the first place most likely)
    string hex = hexnumber;

    // use c++ to do the work for us
    return stoi(hex, nullptr, 16);
}
user904963
  • 1,520
  • 2
  • 15
  • 33
  • @VineetJain Briefly, it's a type that is convertible to any pointer type and stands for that pointer not pointing to something. Before the keyword nullptr, people would use the macro NULL or just put 0. For a more complete answer: http://stackoverflow.com/questions/1282295/what-exactly-is-nullptr – user904963 Nov 23 '13 at 22:37