How would you go about converting a decimal value to hex and then do math? Every example of converting decimal to hex that I have seen creates an array and I wouldn't be able to do math if I did that. Something like this.

15 decimal to hex F
17 decimal to hex 11
F hex + 11 hex = 20

Recommended Answers

All 4 Replies

Decimal and Hexidecimal are encodings of some value. The value itself doesn't change. So do the math in whatever encoding is most comfortable for you then convert the result to desired encoding.

For example, with the values your provided:

15 + 17 = 32
32 decimal is 20 hex

I wanna do everything in Hex. The only 2 ways to convert is to make an array which you can't do math with a char array and the %x option with printf and then you can't do math that way.

To clarify L7Sqr's point:
At the end of the day a number is just a number.
It doesn't matter what base it is in, it ultimately has the same value.
When a number is stored in an int variable, it is actually stored in memory as a binary value. Octal, Hexadecimal and Decimal are just convenient ways of displaying/representing that value.

When we display the value of a variable using printf, it is displayed as decimal by default, because decimal is the most human-readable format.
In order to see it as hex, you need to specify %x or %X (depending on whether you want the hex digits displayed as lower-case or upper-case characters).

If you want to assign a hexadecimal value to an int variable in a C program you can do this:
int hexvalue = 0xA5;
But again, when you output the value of hexvalue via printf, it will be displayed as decimal unless you specify %X.

So, if you are dealing with user input values, you need to parse the strings entered by the users to ensure that they are valid hex values. Then convert the strings to their equivalent int values (using hex, octal or decimal....whatever floats your boat!). You might also want to consider doing some range checking on the values before performing any calculations using standard C maths functions/operators and finally output the results via printf using %X.

That way your users can input hex values as strings, you convert the strings to ints, perform any calculations and output as hex using %X. There is nothing more to it than that!

Here's about the simplest example I can think of:
Note: I haven't done any range checking on any of the values or anything like that, this is just a quick example off the top of my head:

#include <stdio.h>
#include <stdlib.h>

/* Convert a user entered string representing a hex value into an int
 * \param <strValue> The string to convert
 * \param <size> Size of the string
 * \return <int> integer equivalent of hex-string
 */
int hexStrToInt(const char *strValue, int size)
{
        int multiplier = 1; /* start with the units */
        int idx=0, val=0, total=0;
        char digit;

        /* Iterate backwards through the string from the least significant digit */
        for(idx=size-1; idx>=0; --idx)
        {
                digit = strValue[idx];
                if(digit >= '0' && digit <='9')
                        val = atoi(&digit);
                else if(digit >= 'A' && digit <= 'F')
                        val = digit - 55; /* gives us a value between 10 and 15 */

                /* Add the int equivalent of the current hex digit to the total */
                total += val * multiplier;
                multiplier *= 16; /* Set up the multiplier value for the next digit */
        }
        return total; /* Return the resultant int value */
}

int main()
{
        /* Two strings representing user entered hex numbers
         * You'll just have to imagine that we got them from the user,
         * validated them and stripped any leading 0x characters
         * For the sake of brevity, I've hard-coded the strings       */
        const char *strValue1 = "01FF";
        const char *strValue2 = "19EB";

        /* Convert the two user-entered strings to their corresponding int values*/
        int val1 = hexStrToInt(strValue1, 4);
        int val2 = hexStrToInt(strValue2, 4);

        int val3 = 0xA5; /* Assigning a hex value to an int */

        /* Output the sum of the three values as hex.*/
        printf("%s + %s + %X = %X\n", strValue1, strValue2, val3, val1+val2+val3);

        return 0;
}

Alternatively, if you really want to use hex values rather than decimal:
(Comments removed for brevitys sake)

#include <stdio.h>
#include <stdlib.h>

int hexStrToInt(const char *strValue, int size)
{
        int multiplier = 0x1;
        int idx=0, val=0, total=0;
        char digit;

        for(idx=size-1; idx>=0; --idx)
        {
                digit = strValue[idx];
                if(digit >= '0' && digit <='9')
                        val = atoi(&digit);
                else if(digit >= 'A' && digit <= 'F')
                        val = digit - 0x37;
                total += val * multiplier;
                multiplier *= 0x10;
        }
        return total;
}

int main()
{
        const char *strValue1 = "01FF";
        const char *strValue2 = "19EB";

        int val1 = hexStrToInt(strValue1, 4);
        int val2 = hexStrToInt(strValue2, 4);

        int val3 = 0xA5;

        printf("%s + %s + %X = %X\n", strValue1, strValue2, val3, val1+val2+val3);

        return 0;
}

Or hey, let's just go absolutely nuts. Lets use hex for every value in the program (probably a bad idea, but let's see what we get!):

#include <stdio.h>
#include <stdlib.h>

int hexStrToInt(const char *strValue, int size)
{
        int multiplier = 0x1;
        int idx=0x0, val=0x0, total=0x0;
        char digit;

        for(idx=size-0x1; idx>=0x0; --idx)
        {
                digit = strValue[idx];
                if(digit >= 0x30 && digit <= 0x39)
                        val = atoi(&digit);
                else if(digit >= 0x41 && digit <= 0x46)
                        val = digit - 0x37;

                total += val * multiplier;
                multiplier *= 0x10; 
        }
        return total;
}

int main()
{
        const char *strValue1 = "01FF";
        const char *strValue2 = "19EB";

        int val1 = hexStrToInt(strValue1, 0x4);
        int val2 = hexStrToInt(strValue2, 0x4);

        int val3 = 0xA5;

        printf("%s + %s + %X = %X\n", strValue1, strValue2, val3, val1+val2+val3);

        return 0x0;
}

The first example is really easy to read and understand, the second one is a little more obfuscated. But the third one.... Well, that's just silly! It will compile and run, but to read and maintain code like that would be difficult! Much easier to work with decimal in the code and display as hex when required!

I think that proves my point!

After reading your post again, I realise I was doing things the wrong way around. Going the other way - User entering decimal values and converting to hex, would be as simple as this:

#include <stdio.h>

int main()
{
        /* two user entered int values.. Just use your imagination dammit! */
        int userVal1 = 15;
        int userVal2 = 155;

        printf("%d in hex: %X\n", userVal1, userVal1);
        printf("%d in hex: %X\n", userVal2, userVal2);
        printf("%X + %X = %X\n", userVal1, userVal2, userVal1+userVal2);

        return 0;
}

There is nothing more complicated required. As mentioned, all numbers are stored and manipulated in memory as binary. Decimal is displayed by default as a convenience to us humans. To display as hex, simply output the value as hex with %X.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.