Saturday, September 10, 2011

JAVA : Conversion Between Binary, Octal, Decimal and Hexadecimal


This post explains how to do conversion between Binary, Octal, Decimal and Hexadecimal in Java. The java.lang package give us this capability. Following methods do this conversion.

1) toBinaryString(int i): Method that takes an integer type value and returns the string representation of that integer value that will represent it in binary (base 2).

2) toHexString(int i): Method that takes an integer type value and returns the string representation of that integer value that will represent it in hexadecimal (base 16).

3) toOctalString(int i): Method that takes an integer type value and returns the string representation of that integer value that will represent it in octal (base 8).

Example:

public static void main(String[] args) {
    int i = 42;
    System.out.println(i + " as binary is " + Integer.toBinaryString(i));
    System.out.println(i + " as octal is " + Integer.toOctalString(i));
    System.out.println(i + " as octal is " + Integer.toHexString(i));
}

Output :

42 as binary is 101010
42 as octal is 52
42 as octal is 2a

Above example shows conversion of decimal into binary, octal and hexadecimal. We can also do opposite. Convert integer and long with some base (radix) other than 10 by using following two methods. Typically these will be hexadecimal (base 16), binary (base 2) or binary (base 8) numbers.

int i = Integer.parseInt(s, radix);
long l = Long.parseLong(s, radix);

Example:

public static void main(String[] args) {
    System.out.println("Binary 101010 as decimal is " + Integer.valueOf("101010", 2));
    System.out.println("Octal 52 as decimal is " + Integer.valueOf("52", 8));
    System.out.println("Hexadecimal 2a as decimal is " + Integer.valueOf("2a", 16));
}

Output:

Binary 101010 as decimal is 42
Octal 52 as decimal is 42
Hexadecimal 2a as decimal is 42


2 Responses to “JAVA : Conversion Between Binary, Octal, Decimal and Hexadecimal”

Javin @ convert string to int in java said...
December 15, 2011 at 5:37 PM

Nice article, here is my way of converting Decimal to Binary in Java


king said...
December 27, 2011 at 10:45 AM

Thanks for detailed explaination


Post a Comment

© 2011 a2ztechguide.com • All rights reserved.
Blogger Template by Bloggermint