user16146531
user16146531

Reputation:

what does 48 and 55 mean in hex? I found a code that converts from decimal to hex that I posted down below

 // check if temp < 10
        if (temp < 10) {
            hexaDeciNum[i] = temp + 48;
            i++;
        }
        else {
            hexaDeciNum[i] = temp + 55;
            i++;
        }
 
        n = n / 16;
    }

I found this code to convert from decimal to hex but as you can see we have + 48 and + 55 anyone know why did we use these numbers? btw temp is to store the remainder... thanks!

Upvotes: 1

Views: 1215

Answers (2)

Pete Becker
Pete Becker

Reputation: 76458

What the code is doing, badly, is converting a value in the range of 0 to 15 into a corresponding character for the hexadecimal representation of that value. The right way to do that is with a lookup table:

const char hex[] = "0123456789ABCDEF";

hexaDeciNum[i] = hex[temp];

One problem with the code as written is that it assumes, without saying so, that you want the output characters encoded in ASCII. That's almost always the case, but there is no need to make that assumption. The compiler knows what encoding the system that it is targeting uses, so the values in the array hex in my code will be correct for the target system, even if it doesn't use ASCII.

Another problem with the code as written is the magic numbers. They don't tell you what their purpose is. To get rid of the magic numbers, replace 48 with '0' and replace 55 with 'A' - 10. But see the previous paragraph.

In C and C++ you can convert a base-10 digit to its corresponding character by adding it to '0', so

hexaDeciNum[i] = digit + '0';

will work correctly. There is no such requirement for any other values, so that conversion to a letter is not guaranteed to work, even if you use 'A' instead of that hardcoded 65.

And don't get me started on pointless comments:

// check if temp < 10
    if (temp < 10) 

Upvotes: 3

Lubo
Lubo

Reputation: 384

If you look on the ASCII table you will see that the characters for numbers 0..9 are shifted by 48. So, if you take a number e.g. 0 and add 48 to it you will get a character for that number "0".

The same goes for characters if you take number 10 and add 55 to it you will get an "A" character from the ASCII table.

Upvotes: 1

Related Questions