我不明白以下C代码行

时间:2010-08-26 10:04:47

标签: c bit-manipulation bit-shift bitwise-operators

我找到了以下帖子:
Calculate broadcast address from ip and subnet mask以及指向http://lpccomp.bc.ca/netmask/netmask.c

的链接

有人可以解释下面一行,我不明白:

for ( maskbits=32 ; (mask & (1L<<(32-maskbits))) == 0 ; maskbits-- )

尤其是mask & (1L<<(32-maskbits))

3 个答案:

答案 0 :(得分:6)

<<bitwise left shift operator;它将剩余给定数量的值的位移位。因此1L<<(32-maskbits)将值1移至左32-maskbits次。

&bitwise AND operator

因此循环表达式mask & (1L<<(32-maskbits)) == 0测试mask值内的所有位,从低到高。循环将在mask的第一个(最低)非零位停止,此时maskbits将包含该位以上(和包括)位的位数。

E.g。

  • 如果 mask == 0xFFFF mask == 0xFFFFFFFF (== binary 11111111111111111111111111111111),循环将在第一次迭代时停止,maskbits将为32
  • 如果 mask == 0x0001 mask == 0x00000001 (== binary 00000000000000000000000000000001),循环将在第一次迭代时再次停止,maskbits将为32
  • 如果 mask == 0x1000 mask == 0x01000000 (== binary 00000001000000000000000000000000),循环将在第24次迭代时停止,maskbits将为8

答案 1 :(得分:1)

答案 2 :(得分:1)

要了解发生了什么:运行它。

#include <stdio.h> 
#include <iostream>
using namespace std;

char *binary (unsigned int v) {
static char binstr[33] ;
int i ;

binstr[32] = '\0' ;
for (i=0; i<32; i++) {
binstr[31-i] = v & 1 ? '1' : '0' ;
v = v / 2 ;
}

return binstr ;
}

int main(void){  

  unsigned long maskbits,mask;  

mask = 0x01000000;
cout << "MASK IS: " << binary(mask) << "\n";
cout << "32 is: " << binary(32) << "\n\n";
for ( maskbits=32 ; (mask & (1L<<(32-maskbits))) == 0 ; maskbits-- ) {
cout << "maskbits: " << binary(maskbits) << "\n";
cout << "\t(32-maskbits): " << binary((32-maskbits)) << "\n";
cout << "\t1L<<(32-maskbits): " << binary((1L<<(32-maskbits))) << "\n";
cout << "\t(mask & (1L<<(32-maskbits))): " << binary((mask & (1L<<(32-maskbits)))) << "\n\n";

}

cout << "\nFinal maskbits: " << maskbits;

return 0;
}

http://ideone.com/eB8Kp