jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Hexadecimal and decimal convert code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Hexadecimal and decimal convert code" Watch "Hexadecimal and decimal convert code" New topic

Hexadecimal and decimal convert code

Qing Tian

Joined: Aug 17, 2004
Posts: 10
please someone can teach me how to write a java code on convert hexadecimal to decimal and the decimal to hexadecimal.
which is the code not using following tools:
int i = 29;
String octal = Integer.toOctalString(i);
String hex = Integer.toHexString(i);
String binary = Integer.toBinaryString(i);

Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

How would you convert the decimal 132 to hex by hand/ on paper?
How would you convert a7 to decimal without pc?

Qing Tian

Joined: Aug 17, 2004
Posts: 10
on paper that I know
convert 132 to hex is:
132/16 = 8 remainder 4, so the hex will be 84

convert a7 to decimal is:
10(a)* 16 + 7 * 1= 167

I was confused if the number like 24032 and by hand the steps will be:
24032/16=1502 r 0
1502/16 = 93 r 14 (E)
93/16 = 5 r 13 (D)
5/16 = 0 r 5
the hex will be 5DE0
in the java code how the loop divide 16 untill decimal=0 and also the output can display like 5DE0 in order?
(I start learn java on 3 weeks ago so )
did I'm right on calculate? thanks for your help.
[ August 18, 2004: Message edited by: Qing Tian ]
celine mcgowan
Ranch Hand

Joined: Nov 22, 2003
Posts: 36
Hi there!

I was looking into the same problem myself not so long ago! Hard to find the solution, isn't it?!!! Behind the .toHexString etc. all that's happening is:
Convert int to Hex:

To go back to int from hex:

Similarly to convert from int to Binary String:

To go back to int from hex:

Hope this helps... By the way, i find it easier (less cumbersome) to convert to Binary before converting to Hex. When you get the binary number, you're then just converting every four bits to the Hex equivalent...


We've heard that a million monkeys at a million keyboards would eventually reproduce the entire works of Shakespeare. Now, thanks to the Internet, we know this is not true.<br />- Robert Wilensky
Hans Achternaam

Joined: Aug 18, 2004
Posts: 3
Qing, thats the right method to convert from hex to dec.
Qing Tian

Joined: Aug 17, 2004
Posts: 10
thank you all for help, that will help me alot!
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
Here's a 'manual' way

for args[] enter eg
24032 10 16
5DE0 16 10

Qing Tian

Joined: Aug 17, 2004
Posts: 10
thank you Michael that you give me more idea on these codes.
I agree. Here's the link: http://aspose.com/file-tools
subject: Hexadecimal and decimal convert code
It's not a secret anymore!