/* related posts with thumb nails */

### Bitwise operators:

When Bit wise operators are used on operands, they convert the numbers into binary system and then apply bitwise operators. Bit wise operators in Java are:

§ Bitwise AND ( & )

§ Bitwise OR ( | )

§ Bitwise XOR ( ^ )

§ Left shift operator ( << )

§ Right shift operator ( >> )

§ Right shift with zero fill ( >>> )

§ Complement operator (~)

Bitwise AND ( & ): The result of applying AND an bits is 1 if both are 1; otherwise 0.

Ex:

X = 1101

Y = 1110

X & Y = 1100

Bitwise OR ( | ): The result of OR operation is 1 if at least one of the bits has a value 1; otherwise it is 0

Ex:

X = 1101

Y = 1110

X | Y = 1111

Bitwise XOR ( ^ ): The result of XOR is 1 if only one of the bits is 1;

otherwise 0

Ex:

X = 1101

Y= 1110

X ^ Y = 0011

Left shift ( << ): shifts ‘n’ bits left

Ex:

X = 0000 0000 1011 1101

X<<3= 0000 0101 1110 1000

Right shift ( >> ): shifts ‘n’ bits right

Ex:

X = 0000 0000 1011 1101

X>>3= 0000 0000 0001 0111

Complement ( ~): It inverts all the bits. It is a unary operator. Complement of 1 is 0 and complement of 0 is 1.

Ex:

X = 1011

~X =1111 1111 1111 0100

Truth Table:

## A

B

A & B

A | B

A ^ B

0

0

0

0

0

1

0

0

1

1

0

1

0

1

1

1

1

1

1

0

Example:

class p1

{

public static void main(String as[])

{

System.out.println(13&14); // prints 12

System.out.println(13|14); // prints 15

System.out.println(13^14); // prints 3

System.out.println(50<<3); // prints 400

System.out.println(50>>4); // prints 3

System.out.println(50>>>3); // prints 6

System.out.println(~5); // prints -6

}

}

Related Topics: