if (a[i]&(1<<j)) This sentence means to determine whether the a[i] bit of j is 1. 1 << x is to shift 1 to the left by x bits, such as 1 << 3 == 0b1000.
We assume that a[i] = 111 is 32 bits, then the binary of a[i] is 0b0000_0000_0000_0000_0000_0000_0110_1111, 1 << 6 is 0b1000000, then a[i] & 1 << 6 == 0b0000_0000_0000_0000_0000_0000_0100_0000, if the 6th bit of a[i] (the first bit is the 0th bit ) is 1, then the result of a[i] & 1 << 6 is non-0 (the above example). If the 6th bit of a[i] is 0, the result of a[i] & 1 << 6 is 0.
is used to obtain the value of the j-th bit of the integer variable a[i]. When the value of a[i]&(1<<j) is not 0, it means the j-th bit of a[i] is 1. When j=0, get the value of the first bit, when j=1, get the value of the second bit, and so on.
Shift 1 to the left by j bits, and its position is 1. The & operation means that only 1&1 is 1. a[i]&(1<<j) thus retains the value of the j-th bit of a[i], and the other bits are all 0. The if here determines that a[i]&(1<<j) is 0 and outputs 0 instead of 1. The binary version of a[i] is output
if (a[i]&(1<<j))
This sentence means to determine whether thea[i]
bit ofj
is 1.1 << x
is to shift 1 to the left by x bits, such as1 << 3 == 0b1000
.We assume that
a[i] = 111
is 32 bits, then the binary ofa[i]
is0b0000_0000_0000_0000_0000_0000_0110_1111
,1 << 6
is0b1000000
, thena[i] & 1 << 6 == 0b0000_0000_0000_0000_0000_0000_0100_0000
, if the 6th bit ofa[i]
(the first bit is the 0th bit ) is 1, then the result ofa[i] & 1 << 6
is non-0 (the above example). If the 6th bit ofa[i]
is 0, the result ofa[i] & 1 << 6
is 0.is used to obtain the value of the j-th bit of the integer variable a[i]. When the value of a[i]&(1<<j) is not 0, it means the j-th bit of a[i] is 1.
When j=0, get the value of the first bit, when j=1, get the value of the second bit, and so on.
In the loop, from msb to lsb, test each bit.
(1<<j)
Build bitmask.a[i]&(1<<j)
Test whether the corresponding bit is set to1
.Shift 1 to the left by j bits, and its position is 1. The & operation means that only 1&1 is 1. a[i]&(1<<j) thus retains the value of the j-th bit of a[i], and the other bits are all 0. The if here determines that a[i]&(1<<j) is 0 and outputs 0 instead of 1. The binary version of a[i] is output