bitwise shifts

Task condition:

Implement the flipBit method, which changes the value of one bit of a given integer to the opposite.Let's agree that the bits are numbered from the lowest (index 1) to the highest (index 32).

And here is his solution:

public static int flipBit(int value, int bitIndex) {
    return value ^ (1 << bitIndex-1);
}

Question: I can't understand what is happening here:

(1 << bitIndex-1)

Explain pozh-a.

Author: Kromster, 2017-01-30

3 answers

Question: I can't understand what is happening here: (1

There is a shift of bits to the left (or stupidly raising the two to the power) bitIndex-1

In fact, you can see more details here

In short, 1 can be represented roughly as 00000001

<< - bitwise left shift

As a result, for example, if bitIndex is 3, then 1 << 3 (we shift one by three digits to the left) turns out

00001000 // 8

And when bitIndex - 1 it turns out accordingly:

bitIndex - 1  → 1 << 2 → 00000100 // 4

Although in the end, what is the value in the decimal system is not important, but it is simple, for the record

 2
Author: Алексей Шиманский, 2017-04-13 12:53:25

Question: I can't understand what is happening here:

   (1 << bitIndex-1)

Here, the bits in 1 are shifted to the left by bitIndex-1 positions.

 1
Author: post_zeew, 2020-06-12 12:52:24

The bits are shifted to the left, and the new bits are replaced by zeros. In fact, this is the raising of a deuce to a power.

1

 1
Author: Кирилл Малышев, 2017-01-30 19:37:43