Wednesday 24 May 2023

Understanding Bitwise Operator in Java 2023

 Understanding Bitwise Operator in Java

Bitwise operators are used to perform operations on bits and binary numbers. They are useful for low level programming and implementing algorithms.

Here are the main bitwise operators in Java:

& (AND) - Sets each bit to 1 if both bits are 1.

| (OR) - Sets each bit to 1 if one of two bits is 1.

^ (XOR) - Sets each bit to 1 if only one of two bits is 1.

~ (NOT) - Inverts all the bits.

<< (Left Shift ) - Shifts left by pushing zeros in from the right and lets the leftmost bits fall off.b550 vs x570

(Right Shift) - Shifts right by pushing copies of the leftmost bit in from the left, and lets the rightmost bits fall off.

(Zero fill right shift) - Shifts right like >>, but fills in resulting bits with 0 instead of copying.

For example:

int a = 5; //0101 in binary
int b = 3; //0011 in binary

//AND
int result = a & b; // result is 1 (0001)

//OR
result = a | b; // result is 7 (0111)

//XOR
result = a ^ b; // result is 6 (0110)

//NOT
result = ~a; // result is -6 (-0110) in 2's complement

Bitwise operators provide low level manipulation of binary data that can be useful for optimizing certain algorithms and working with hardware. They allow you to manipulate individual bits of a number.

Hope this overview of Java's bitwise operators helps! Let me know if you have any other questions.

No comments:

Post a Comment

Easily Transfer/Move OS to Another Hard Drive in Windows 10/11 2023

  Easily Transfer/Move OS to Another Hard Drive in Windows 10/11 2023 Here's how you can easily transfer or move your OS to another hard...