Some times we need the binary, hexadecimal or octal representation of the integer. In java you can easily have this with Integer class in one line.
Wrapper class of int, Integer has static methods to achieve this easily. Integer contains static methods like toBinaryString
, toHexString
and toOctalString
to convert number to specific number system representation,but note that these methods return String.
Please consider following example,
public class NumberToBHO { public static void main(String[] args) { int number = 10; System.out.println(Integer.toBinaryString(number)); System.out.println(Integer.toHexString(number)); System.out.println(Integer.toOctalString(number)); } }
In above code we will have following output,
1010 a 12
Kindly note that all these static methods return the String representation of the number in specific number system. As we can see for number 10 we have a in hexadecimal. Moreover , you can not directly parse this back to the String.So, Integer.parseInt(1010)
will obviously won’t give you 10 that is quite understandable.
Further more for long types you can have same static methods in wrapper of long, Long. Check out the same,
public class NumberToBHO { public static void main(String[] args) { long numberL = 1000000000; System.out.println(Long.toBinaryString(numberL)); System.out.println(Long.toHexString(numberL)); System.out.println(Long.toOctalString(numberL)); } }
and for above code we will have the following output,
111011100110101100101000000000 3b9aca00 7346545000
Moreover you can directly pass the int to Long methods as long can handle int but vice versa is not valid.On the other hand for the floating point number types like Double and Float we have only toHexString
methods. There is an indirect way to convert floating point number to binary String representation, we will discuss that in upcoming blog posts.
One thought on “Number to Binary, Hexa, Octa String”