有人可以向我解释这一行吗? c | = 1 << i;

我最近启动了C,由于某些原因,我无法得到这行c | = 1

我在网上发现此函数的目的是从数组中获取最低有效位,然后将其合并,并作为字节返回。

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

有人可以用1和0解释这个例子吗?我认为这将非常有帮助。谢谢!

kotoko520 回答:有人可以向我解释这一行吗? c | = 1 << i;

好吧

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个字节中每个字节的最低有效位的值

我敢打赌,如果我真的想尝试的话,可以对其进行更密集的编码,但这可能是针对性能:)

本文链接:https://www.f2er.com/3148715.html

大家都在问