Thursday, 26 April 2018

Core Java: Bit-Shift Operator

Bit-shift operators perform left or right shift on an operand by a specified number of bits. Right-shift can be either signed-extended (>>) (padded with signed bit) or unsigned-extended (>>>) (padded with zeros). Left-shift is always padded with zeros (for both signed and unsigned).
 
Operator
Usage
Description
<< 
operand << number
Left-shift and padded with zeros
>> 
operand >> number
Right-shift and padded with sign bit (signed-extended right-shift)
>>> 
operand >>> number
Right-shift and padded with zeros (unsigned-extended right-shift)
 
Example
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class BitShiftTest {
   public static void main(String[] args) {
      int x = 0xAAAA5555;               // a negative number (sign bit (msb) = 1)
      int y = 0x55551111;               // a positive number (sign bit (msb) = 0)
      System.out.printf("%d%n", x);     // -1431677611
      System.out.printf("%d%n", y);     // 1431638289
      System.out.printf("%08X%n", x<<1);  // 5554AAAAH
      System.out.printf("%08X%n", x>>1);  // D5552AAAH
      System.out.printf("%d%n", x>>1);    // negative
      System.out.printf("%08X%n", y>>1);  // 2AAA8888H
      System.out.printf("%08d%n", y>>1);  // positive
      System.out.printf("%08X%n", x>>>1); // 55552AAAH
      System.out.printf("%d%n", x>>>1);   // positive
      System.out.printf("%08X%n", y>>>1); // 2AAA8888
      System.out.printf("%d%n", y>>>1);   // positive

      // More efficient to use signed-right-right to perform division by 2, 4, 8,...
      int i1 = 12345;
      System.out.println("i1 divides by 2 is " + (i1 >> 1));
      System.out.println("i1 divides by 4 is " + (i1 >> 2));
      System.out.println("i1 divides by 8 is " + (i1 >> 3));
      int i2 = -12345;
      System.out.println("i2 divides by 2 is " + (i2 >> 1));
      System.out.println("i2 divides by 4 is " + (i2 >> 2));
      System.out.println("i2 divides by 8 is " + (i2 >> 3));
   }
}

  Types and Bitwise Operations
 
The bitwise operators are applicable to integral primitive types: byte, short, int, long and char. char is treated as unsigned 16-bit integer. There are not applicable to float and double. The '&', '|', '^', when apply to two booleans, perform logical operations. Bit-shift operators are not applicable to booleans.
Like binary arithmetic operations:
 
·        byte, short and char operands are first promoted to int.
 
·        If both the operands are of the same type (int or long), they are evaluated in that type and returns a result of that type.
 
·        If the operands are of different types, the smaller operand (int) is promoted to the larger one (long). It then operates on the larger type (long) and returns a result in the larger type (long).

No comments:

Post a Comment

Please write your view and suggestion....