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

问题描述 投票:0回答:1

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

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

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 << i;与c = c |相同1 <

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

c bitwise-operators bit bit-shift
1个回答
0
投票
Well, 1<<I should be 1 followed by I zeros (binary)--so

1<<0 would be 0001, 1<<1 would be 0010, 1<<2 would be 0100

When that is ored with what's in C it means to force-set that bit, so:

if you take 0000 | 0010 you'll get 0010
0010 | 0010 = 0010 as well
1111 | 0010 = 1111 (No change if the bit is already 1)
1101 | 0010 = 1111 (Just sets that one bit)

So essentially it set's the ith bit in C (starting from the least significant)
© www.soinside.com 2019 - 2024. All rights reserved.