我最近启动了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解释这个例子?我认为这将非常有帮助。谢谢!
好,
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个字节中每个字节的最低有效位的值
我敢打赌,如果我真的想尝试的话,可以对其进行更密集的编码,但这可能是针对性能:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句