Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hexadecimal and decimal convert code

 
Qing Tian
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);

thanks
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How would you convert the decimal 132 to hex by hand/ on paper?
How would you convert a7 to decimal without pc?
 
Qing Tian
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...

Cheers,
Celine
 
Hans Achternaam
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Qing, thats the right method to convert from hex to dec.
 
Qing Tian
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you all for help, that will help me alot!
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a 'manual' way

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

 
Qing Tian
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you Michael that you give me more idea on these codes.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic