How to convert integer into binary, octal and hex in Java

Java programming topics
Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to convert integer into binary, octal and hex in Java

Post by Neo » Sat Nov 28, 2009 4:21 pm

The java.lang package provides the facility for converting the data integer into binary, octal, and hexadecimal. The following program helps you to convert into these. toBinaryString() method converts integer type data into binary, toHexString() method converts integer type into hexadecimal and toOctalString() method converts integer into octal type data.

Description of code:

toBinaryString(int in):
This is the method that takes an integer type value and returns the string representation of unsigned integer value that will represent the data in binary (base 2).

toHexString(int in):
This is the method that takes an integer type value and converts in hexadecimal or in an unsigned integer (base 16).

toOctalString(int in):
This is the method that takes an integer type value and converts it into octal type data. The octal type data has base 8.

Code: Select all

public class DataConversion{
  public static void main(String[] args) {
    System.out.println("Data types conversion example!");
    int in = 243;
    System.out.println("Integer: " + in);
    //integer to binary
    String by = Integer.toBinaryString(in);
    System.out.println("Byte: " + by);
    //integer to hexadecimal
    String hex = Integer.toHexString(in);
    System.out.println("Hexa decimal: " + hex);
    //integer to octal
    String oct = Integer.toOctalString(in);
    System.out.println("Octal: " + oct);
  }
}
Post Reply

Return to “Java Programming”