Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

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

 
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..
 
Wanderer
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
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.
 
Happily living in the valley of the dried frogs with a few tiny ads.
ScroogeXHTML - small and flexible RTF to HTML converter library
https://coderanch.com/t/710903/ScroogeXHTML-RTF-HTML-XHTML-converter
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!