Rajinder,
this is a nice solution but allow me to doubt that during the exam one will be willing to perform all those computations. Moreover, your solution does not show how to manipulate bits and this is a very important topic for the purpose of the certification when dealing with shift operators and the like.
A much more elegant solution that all computer scientists, programmers and students should know at the very beginning is to be able to decompose any number in powers of 2. And from there on you can do everything.
I take 259 to show you how easy it is.
1. write the powers of two from the right to the left on a piece of paper, that is 2 power 0, 2 power 1, 2 power 2, and so on:
256 128 64 32 8 4 2 1
2. Decompose your number into those numbers, that is, try to find all powers of two that you can add together and get 259 (there is only one solution). You write a 1 under each number you choose and a 0 under each other number. Easy:
256 128 64 32 16 8 4 2 1
1 0 0 0 0 0 0 1 1
That is 256+2+1 = 259.
100000011 is your binary representation of 259. From there on you can do two things, either convert to hexadecimal (radix 16) or to octal (radix 8).
3. If you want ot convert to hexadecimal, group your binary sequence by groups of 4 bits (because the biggest value a group of 4 bits can have is 15) beginning on the right side and pad the incomplete group on the left with 0's, like this:
0001 0000 0011
Then you just have to take one binary group after another and convert its value to hexadecimal (values range form 0 to F).
So we have 103 which we write 0x103 to signify that the number is in hexadecimal and that's it...
4. If you want ot convert to octal, group your binary sequence by groups of 3 bits (because the biggest value a group of 3 bits can have is 7) beginning on the right side and pad the incomplete group on the left with 0's, like this:
100 000 011
Then you just have to take one binary group after another and convert its value to its octal equivalent (values range from 0 to 7).
So we have 403 which we write 0403 to signify that the number is in octal and that's it...
So 259 in decimal is
- 100000011 in binary
- 0x103 in hexadecimal
- 0403 in octal
You must have noticed by now that the latter three are tightly coupled. Do learn this technique because it is very important to know it.
If you want more information, please read the following link
Javaranch:Cat and Mouse Games with Bits or do a search in this forum.
[ February 18, 2002: Message edited by: Valentin Crettaz ]
[ February 18, 2002: Message edited by: Valentin Crettaz ]