Java bitwise operators
Created By: chatGPT
Bitwise operators are used to perform operations on bits in binary representations of integers. They operate at the bit level and can be very efficient for certain tasks. Java provides several types of bitwise operators, including AND, OR, XOR, NOT, left shift, and right shift.The main bitwise operators in Java are:
1. AND (
&
): The result is 1 if both bits are 1.int a = 12; // In binary: 1100
int b = 5; // In binary: 0101
int result = a & b; // Result: 4 (0100)
2. OR (
|
): The result is 1 if at least one of the bits is 1.int result = a | b; // Result: 13 (1101)
3. XOR (
^
): The result is 1 if the bits are different.int result = a ^ b; // Result: 9 (1001)
4. NOT (
~
): The result inverts the bits.int result = ~a; // Result: -13 (in binary: 0011 0011...1100)
5. Left Shift (
<<
): Shifts bits to the left, filling with 0s. Effectively multiplies the number by 2 for each shift.int result = a << 2; // Result: 48 (1100 becomes 110000)
6. Right Shift (
>>
): Shifts bits to the right, preserving the sign bit. Effectively divides the number by 2 for each shift.int result = a >> 2; // Result: 3 (1100 becomes 11)
7. Unsigned Right Shift (
>>>
): Shifts bits to the right, filling with 0s, regardless of the sign bit.int result = a >>> 2; // Result: 3 (same as >> for positive numbers)
Here is an example of how to use bitwise operators in Java:
public class BitwiseExample {
public static void main(String[] args) {
int a = 12;
int b = 5;
System.out.println("a & b: " + (a & b)); // 4
System.out.println("a | b: " + (a | b)); // 13
System.out.println("a ^ b: " + (a ^ b)); // 9
System.out.println("~a: " + (~a)); // -13
System.out.println("a << 2: " + (a << 2)); // 48
System.out.println("a >> 2: " + (a >> 2)); // 3
System.out.println("a >>> 2: " + (a >>> 2)); // 3
}
}