Binary Literals - Java @ Desk

Wednesday, August 20, 2014

Binary Literals



Binary Literals

In Java SE 7, the integral types (byte, short, int, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number.





The following examples show binary literals:

byte x = (byte) 0b00000010; // 8 –bit Binary
short y = (short) 0b0000000000000101; //16 - bit Binary
String z = Integer.toBinaryString(2147483647);
int z1 = Integer.parseInt(Integer.toBinaryString(2147483647), 2);
int a = 0B100; // The B can be upper or lower case.

System.out.println("value of X:" + x);
System.out.println("value of Y:" + y);
System.out.println("value of Z:" + z);
System.out.println("value of Z1:" + z1);
System.out.println("value of A:" + a);


value of X:2
value of Y:5
value of Z:1111111111111111111111111111111
value of Z1:2147483647
value of A:4


Binary literals can make relationships among data more apparent than they would be in hexadecimal or octal. For example, each successive number in the following array is rotated by two bit:

public static final int[] phases = {
  0b00110001,
  0b11000100,
  0b00010011,
  0b01001100
}


In hexadecimal, the relationship among the numbers is not readily apparent:

public static final int[] phases = {
  0x31, 0xC4, 0x13, 0x4C
}


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.





No comments:

Post a Comment