Could someone explain to me how hexadecimal works? eg, how does 0x12 = 18
This is a discussion on Hexadecimal within the C++ Programming forums, part of the General Programming Boards category; Could someone explain to me how hexadecimal works? eg, how does 0x12 = 18...
Could someone explain to me how hexadecimal works? eg, how does 0x12 = 18
Okay so Hexadecimal is Base 16, which you probably already know. Humans usually use Base 10, or decimal. Hex has the following symbols:
0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
And is also prefixed with 0x .
Your number is 0x12. It is fairly easy to convert to decimal. Take the total number of digits and subtrat one. This will give us one in this case. Then starting left to right, multiply by 16 raised to the x power. Example 0x12.
( 1 * 16^1 ) + (2 * 16^0) = 18
You just decrease in power as you go to the right.
Perhaps another example
0x11C - 3 digits , so start with power 2.
1*(16)^2 + 1*(16)^1 + 12*(16)^0 =
256 + 16 + 12 = 284
Hope this cleared it up for you.
Yup, thanks. Also, is there an easy way to convert numbers into hexadecimal? There must be, I just don't know it.
Basically you just work backwards. Let's take that 284 example in decimal. We want to convert that to Hexadecimal.
What is the largest power to the 16 that will go into 284. The answer is 2. 16^2 = 256. Because 16^3 = 4096 that is too big. So how many times does 256 go into 284? 1, so our first digit is 1. Let's write that out.
0x1 is what we have so far. Now we subtract 256 from our original number to obtain 28. 16^1 = 16 so that will go in there. It goes into 28 once, so our next digit is 1 again.
0x11 so far.
Then we subtract to get to get 12. Well 16^0 is 1 so that goes into 12 , 12 times, so 12 is C in hex.
0x11C is our final answer. Any particular one's you don't understand?
Oh yea, and would converting hexadecimals into numbers be the same as vice versa except work backwards on working backwords?
I'm sure there probably are but you could easily just write your own functions.
edit: Didn't understand your last question
"...the results are undefined, and we all know what "undefined" means: it means it works during development, it works during testing, and it blows up in your most important customers' faces." --Scott Meyers
If by normal numbers you mean integers, then I just told you how.
This will print the hexadecimal value of a number.
Code:#include <iostream> using namespace std; int main(void) { int a; cout << "Enter number to convert to hex:"; cin >> a; cout << a << " = " << hex << a << " hex" << endl; return 0; }
Here is the source for a base* to base* converter I made.
Q
That's ok, I got hold of that a long time ago, plus I just wanted to know how hexadecimal worked.