Bitwise Shift and Assignment Operators

Author: Tatyana Milkina

1. Bitwise Operations

The following table presents bitwise operations used in the Java language:

Operation
Description
~
Bitwise unary NOT operation (NOT, complement)
&
Bitwise logical AND operation (AND, bitwise conjunction)
|
Bitwise logical OR operation (OR, bitwise disjunction)
^
Bitwise logical exclusive OR operation (XOR)

Bitwise operators are applied to integer types long, int, short, byte, and char. Bitwise operators are applied to each individual bit of each operand.

Results of bitwise logical operations

A

B

A | B

A & B

A ^ B

~A

0

0

0

0

0

1

1

0

1

0

1

0

0

1

1

0

1

1

1

1

1

1

0

0

1.1. Bitwise OR (OR, |)

The resulting bit from the OR operation is 1 if the corresponding bit in either operand is 1.
'  00101010   42
 | 00001111   15 
   -------------- 
   00101111   47
'

1.2. Bitwise AND (AND, &)

The resulting bit from the AND operation is 1 if the corresponding bits in both operands are 1. In all other cases, the resulting bit is 0.
' 00101010   42 
& 00001111   15
  --------------
  00001010   10
'

1.3. Bitwise Exclusive OR (XOR, ^)

The resulting bit from the XOR operation is 1 if the corresponding bit is 1 in only one of the operands. In all other cases, the resulting bit is 0.
' 00101010  42 
^ 00001111  15
 --------------
  00100101  37 
'

1.4. Bitwise NOT (NOT, ~)

The unary NOT operator (~), also called the bitwise complement, inverts all the bits of the operand.
~ 00101010   42
-----------------
  11010101

Let’s now look at how bitwise operations are used in a program. The following example also shows the use of the Integer.toBinaryString() method, which converts a decimal value to binary:

public class BitwiseExample1 {
    public static void main(String[] args) {
        int a = 3;
        int b = 6;
        int c = a | b;
        int d = a & b;
        int e = a ^ b;
        int f = ~b;
        System.out.println("a = " + Integer.toBinaryString(a));
        System.out.println("b = " + Integer.toBinaryString(b));
        System.out.println("a | b = " + Integer.toBinaryString(c));
        System.out.println("a & b = " + Integer.toBinaryString(d));
        System.out.println("a ^ b = " + Integer.toBinaryString(e));
        System.out.println("~ b = " + Integer.toBinaryString(f));
    }
}

2. Bit Shifts in Java

Operation
Description
>>
Right shift (arithmetic shift)
>>>
Right shift with zero fill (unsigned shift)
<<
Left shift
Bitwise shifts move all binary digits of a value by a specified number of positions.

General form:

value << number
For example:
34<<3, 56>>2, 78>>>1
To understand how the shift works, it's better to look at examples with binary numbers:
0001<<1 = 0010
0100>>1 = 0010

When shifting negative numbers, there's a difference between using >> and >>>. The >> operation extends the sign (leftmost) bit to the right, while >>> fills with zeros. For positive numbers, the result is the same.

The byte and short types are promoted to int during expression evaluation.

Example of bit shifts:

int i = 192;
i       00000000 00000000 00000000 11000000 (192)
i<<1    00000000 00000000 00000001 10000000 (384)
i>>1    00000000 00000000 00000000 01100000 (96)
i>>>1   00000000 00000000 00000000 01100000 (96) 
int i = -192; (binary in two's complement)
i       11111111 11111111 11111111 01000000 (-192) 
i<<1    11111111 11111111 11111110 10000000 (-384)
i>>1    11111111 11111111 11111111 10100000 (-96)
i>>>1   01111111 11111111 11111111 10100000 (2147483552)
public class BitwiseExample2 {
    public static void main(String[] args) {
        byte a = 64; //0100 0000
        byte b;
        int i = a << 2; // 1 0000 0000
        b = (byte) (a << 2); //0000 0000
        System.out.println("a = " + a);
        System.out.println("i = " + i);
        System.out.println("b = " + b);
    }
}

3. Bitwise Assignment Operations

There are also bitwise operations with assignment:

Operation
Description
&=
Bitwise AND with assignment
|=
Bitwise OR with assignment
^=
Bitwise XOR with assignment
>>=
Right shift with assignment
>>>=
Unsigned right shift with assignment
<<=
Left shift with assignment

4. Practical Use of Bitwise Operations

Bitwise operations have many practical applications. Let's look at some of them:

4.1. Checking Evenness

x & 1 checks whether a number is even. If the result is 0, the number is even; if 1 — odd.

4.2. Dividing a Number by Two

  • x<<1 – multiplication by 2.
  • x>>1 - division by 2 (truncating any remainder).

4.3. Encrypting a Number

The XOR operation, when applied twice to the same bit pattern, restores the original value. This can be used for data encryption during transmission:

  C = A ^ B

  A = C ^ B 

Imagine you need to send the number 560 — a bank card PIN code. If an attacker intercepts the message, they’ll get the PIN and can use it. Only the sender and receiver should know the PIN. To prevent this, let's come up with a number — a mask — and share it with the recipient in advance. Before sending the PIN, we encrypt it using XOR: message ^ mask. If intercepted, the message can't be decrypted without the mask. The recipient decrypts the message using the same mask: message ^ mask.

Here's a code example:

public class BitwiseExample3 {
    public static void main(String[] args) {
        int message = 560;
        int maska = 67;
        int codedMessage = message ^ maska;
        int receivedMesssage = codedMessage ^ maska;
        System.out.println("message = " + message);
        System.out.println("message = " + Integer.toBinaryString(message));
        System.out.println("codedMessage = " + codedMessage);
        System.out.println("codedMessage = " + Integer.toBinaryString(codedMessage));
        System.out.println("receivedMesssage = " + receivedMesssage);
        System.out.println("receivedMesssage = " + Integer.toBinaryString(receivedMesssage));
    }
}

4.4. Applying a Bitmask

A bitmask lets you extract specific bits from a sequence. For example, we have a mask 00100100. It lets us extract only the bits set in this mask — here, the 3rd and 7th bits. To do this, perform a bitwise AND between the mask and the target number:
      001010101 
&     000100100 
---------------- 
      000000100
Курс 'Java для начинающих' на Udemy Курс 'Java для начинающих' на Udemy
Read also:
Comments