I'm almost giving up on this problem.

How to convert an integer to it's hexadecimal equivalent.

I'm not looking to printout the hexadecimal equivalent of the integer in printf() but for a hexadecimal number.

The computer stores that integer as a series of bits and bytes, iow in base 2. It's only for our own convenience as humans who're used to thinking in base 10 that most programming environments use base 10 for inputing and outputing numerical data.
To output in another base, most …

## All 3 Replies

It is quite simple if you know the maths behind this.

All these are just bases in which you can write your any number. For example, n = 9 can be written as 1001 in base 2(binary) and it is 9 in base 10(decimal).

How am I writing 9 as 1001 in base 2?

Start with 9 and divide it it with 2. Take Quotient and remainder. Here, Quotient = 4 and remainder = 1. Now, Save this remainder anywhere. Now take quotient = 4 and again divide it by 2. Again, Quotient is 2 and remainder =0. Add this remainder where you have stored initial remainder. Repeat this until you get remainder 1 or 0. Note: Save the last remainder also. Still, you didn't get the answer.

Here is code snippet for binary.

``````Void convertTOBinary(int n)
{
while(n>0)
{
//save this remainder
int remainder = n%2;
n/=2;
}
}
``````

So, How to do for Hexadecimal. Can you relate now? When base was2, I was diving by 2, but in your case base is 16. So you will divide by 16 here as per the case. Difference is that in base 2, you can have only 2 remainders, but in Hexa, you can have 16 remainders. Remainders between 0-9 will be as it is, but after 9 it will be like this:

``````10 = A
11 = B
12 = C
.
.
.
.
``````

I hope you get the point. Whenever remainder is 10 or 11 or whatever, put if-else condition for A or B or like that. Still facing problem, Feel free to ask your doubts. Hope this helps.

The computer stores that integer as a series of bits and bytes, iow in base 2. It's only for our own convenience as humans who're used to thinking in base 10 that most programming environments use base 10 for inputing and outputing numerical data.
To output in another base, most languages have either built in or 3rd party libraries available to do just that, no need to reinvent the wheel.

Don't forget that the hexadecimal representation of an integer is a string.