Java Certification, Programming, JavaBean and Object Oriented Reference Books
Java Binary Representation Of Integers

This tutorial will take you step by step through the process of understanding and using operators that act on individual bits. The best way to learn is to compile and run these programs yourself (copy, paste, compile and run !). Comments such as /* this is a comment */ or // this is another comment are inserted to explain what does the line of code do. The programs are kept simple for the purpose of concentrating on the main idea in question.

Example 1 : integer types in binary form

In this example, it is shown how a positive integer is represented binary form (using 1 and 0 only).

  
class Bits1{ 

   public static void main(String args[]){
      int i = 11;
      String sb = Integer.toBinaryString(b);
      System.out.println("11 in binary: "+sb);
    }
}

Check that the output is : 1011 ( 11 = 1*2^3+0*2^2+1*2^1+1*2^0)

Binary form of any number can be obtained by successive divisions of the given number by 2 :

11/2 = 5 + 1/2

5/2 = 2 + 1/2

2/2 = 1 + 0/2

1/2 = 0 + 1/2

now read the binary form starting from the last 1: 1011

NOTE: do not forget that integers use 32 bits so all the zeros on the left have been ignored.

Example 2 : integer types in binary form

In this example, it is shown how a negative integer is represented in binary form (using 1 and 0 only).java uses an encoding known as two's complement. Negative numbers are obtained by changing 1's into 0's and vice versa then adding 1.

  
class Bits1{ 

   public static void main(String args[]){
      int i = -11;
      String sb = Integer.toBinaryString(b);
      System.out.println("-11 in binary: "+sb);
    }
}

Check that the output is : 11111111111111111111111111110101

Binary form of any negative integer number can be obtained as follows:

the binary form of 11 using all 32 bits is:

00000000000000000000000000001011

to obtain the binary form of -11, invert 1's into 0's and 0's into 1's in the binary form of 11

11111111111111111111111111110100

now add 1

11111111111111111111111111110101 , and this is -11 in binary form.

Return to : Java Programming Hints and Tips