谁能给我解释一下这条线? c |= 1 << 我;

Can anyone explain me this line? c |= 1 << i;

我最近开始使用 C,但由于某些原因我无法获得这一行 c |= 1 << i;

我在网上找到的这个函数的作用是从一个数组中取出最低位然后合并,return作为一个字节。

unsigned char getlsbs(unsigned char* p)
{
        int i;
        unsigned char c = 0;
        for(i = 0; i < 8; i++)
        {
                int a = p[i] & 1;
                if(a)
                {
                        c |= 1 << i;
                }
        }
        return c;
}

c |= 1 << 我;与 c = c | 相同1 << 我;正确吗?

谁能用1s和0s的例子解释一下?我认为这会很有帮助。谢谢!

嗯,

1<<i 

应该是 1 后接 i 个零(二进制)--所以

1<<0 = 0001
1<<1 = 0010
1<<2 = 0100

当它与 C 中的内容进行或运算时,意味着强制设置该位,因此:

if you take 0000 | 0010 you'll get 0010

c val| mask = result
--------------------
0010 | 0010 = 0010 as well
1111 | 0010 = 1111 (No change if the bit is already 1)
1101 | 0010 = 1111 (Just sets that one bit)
xxxx | 0010 = xx1x (All the other bits remain the same)

最后将结果存储回 c。

所以基本上它设置了 c 中的第 i 位(从最低位开始为零)。

更多详情:

// Loop through the first 8 characters in p
for(i = 0; i < 8; i++)
{
    // Grab the least significant bit of the i'th character as an int (1 or 0)
    int a = p[i] & 1;
    // If it happens to be set (was a 1)
    if(a)
    {
        // Set the corresponding (i'th) bit in c
        c |= 1 << i;
    }
}

因此,如果 p 的第一个值的 lsb 为 1,则 c 的 lsb 将为 1

如果 p 中的第二个字节的 lsb 为 1,则 c 的第二位将为 1

等等

结果是C的每一位都会取P的前8个字节的每一个最低有效位的值

我敢打赌,如果我真的想尝试的话,它可以编码得更密集,但这可能是为了提高性能:)