c++ - 这段代码中,a[i]&(1<<j)改怎么理解?
ringa_lee
ringa_lee 2017-04-17 15:21:37
0
4
741

将十进制的ip地址转化为二进制的ip地址

ringa_lee
ringa_lee

ringa_lee

reply all(4)
黄舟

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.

阿神

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 to 1.

洪涛

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template