PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] What do 48 and 87 values refer to when converting hexadecimal to decimal number in C?

 August 10, 2022     base, c, decimal, hex, numbers     No comments   

Issue

I am trying to understand the process of converting a hexadecimal number to its decimal equivalent, in particular when converting each hexadecimal digit to its decimal value.

Say when the digit i of hexVal equals any characters ranging from '0' to '9', its decVal equals the hexVal subtracted by 48 and then timed by the digitBase:

if ((hexVal[i] >= '0') && (hexVal[i] <= '9')) {
    decVal += (hexVal[i] - 48) * digitBase;
    ...
}

I understand that 48 is ASCII value of '0'. What I am in doubt with is where the values 55 and 87 come from when digit i of hexVal equals the ranges 'A' to 'F' and 'a' to 'f':

else if ((hexVal[i] >= 'A') && (hexVal[i] <= 'F')) {
    hexToDec += (hexVal[i] - 55) * digitBase;
    ...
}

and

else if ((hexVal[i] >= 'a') && (hexVal[i] <= 'f')) {
    hexToDec += (hexVal[i] - 87) * digitBase;
    ...
}

The code blocks above are extracted from the following function which works well to convert hexadecimal numbers to their equivalent decimals.

int conv_hex_to_dec(char hexVal[]) {

    int hexToDec = 0;
    int len = strlen(hexVal);
    int digitBase = 1; 

    // Extract hex characters as digits from last character
    for (int i = len - 1; i >= 0; i--) {

        if ((hexVal[i] >= '0') && (hexVal[i] <= '9')) {
            hexToDec += (hexVal[i] - 48) * digitBase;
            digitBase = digitBase * 16;
        }

        else if ((hexVal[i] >= 'A') && (hexVal[i] <= 'F')) {
            hexToDec += (hexVal[i] - 55) * digitBase; 
            digitBase = digitBase * 16;
        }
        else if ((hexVal[i] >= 'a') && (hexVal[i] <= 'f')) {
            hexToDec += (hexVal[i] - 87) * digitBase; 
            digitBase = digitBase * 16;
        }
        else {
            printf("Invalid hex val");
        }
    }

    return hexToDec;
}

Any explanation will be much appreciated.

Thanks.


Solution

48 is the ASCII code for '0'; the ASCII codes for 'A' and 'a' are 65 (55 = 65-10) and 97 (87 = 97 - 10) respectively.



Answered By - Scott Hunter
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing