Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to convert a number to Hexadecimal or Octal format..

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Can anyone please tell me, what method can we use to convert a decimal number to Hexadecimal/Octal and vice-versa?
Thanks..
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Integer class has a variety of methods you can choose between.
Assuming you're starting with a String which represents a number in decimal, and you want a String representing it in octal:
<code><pre> int value = Integer.parseInt(decimalString);
String octalString = Integer.toOctalString(value);</pre></code>
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have to convert a character value to a hex or Octal.
Example : char[] c = new char[10]; Now all the elements would be initialized to " ". How do we convert an array element (say c[5]) value to a hex or octal. Should we use the wrapper class Character for this?
Thanks..

 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of the wrapper classes, only Integer and Long have the full set of conversion methods you need. But since char is an integral type, so you pass it to a method which accepts an integer argument - it's a widening conversion, which means no cast is necessary. (i.e. since the compiler knows that any char can be represented by an int, it will do the conversion for you without you needing to coax it.) So:
<code><pre> String octalString = Integer.toOctalString(c[5]);</pre></code>

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jim.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic