我不明白以下 C 代码行
我发现了以下线程:
根据 IP 和子网掩码计算广播地址,链接如下到 http://lpccomp.bc.ca/netmask/netmask.c
有人可以吗请解释以下行,我不明白:
for ( maskbits=32 ; (mask & (1L<<(32-maskbits))) == 0 ; maskbits-- )
尤其是 mask & (1L<<(32-掩码位))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
<<
是按位左移运算符;它将值的位向左移动给定量。因此,1L<<(32-maskbits)
将值 1 向左移动32-maskbits
次。&
是按位 AND 运算符。所以循环表达式
mask & (1L<<(32-maskbits)) == 0
从低到高测试mask
值内的所有位。循环将在mask
的第一个(最低)非零位处停止,此时maskbits
将包含该位上方(并包括该位)的位数。例如,
mask == 0xFFFF
mask == 0xFFFFFFFF (== binary 11111111111111111111111111111111)
,循环将在第一次迭代时停止,并且
将为32mask == 0x0001
mask == 0x00000001 (== binary 00000000000000000000000000000001)
, >maskbitsmaskbits
将为 32mask == 0x1000
mask == 0x01000000(== 二进制 00000001000000000000000000000000),
,循环将在第 24 次迭代时停止,并且maskbits
将为 8<<
is the bitwise left shift operator; it shifts the bits of a value left by the given amount. Thus1L<<(32-maskbits)
shifts the value 1 to the left32-maskbits
times.&
is the bitwise AND operator.So the loop expression
mask & (1L<<(32-maskbits)) == 0
tests all the bits within the value ofmask
, from lower to higher. The loop will stop on the first (lowest) nonzero bit ofmask
, at which pointmaskbits
will contain the number of bits above (and including) that bit.E.g.
mask == 0xFFFF
mask == 0xFFFFFFFF (== binary 11111111111111111111111111111111)
, the loop will stop on the first iteration, andmaskbits
will be 32mask == 0x0001
mask == 0x00000001 (== binary 00000000000000000000000000000001)
, the loop will again stop on the first iteration, andmaskbits
will be 32mask == 0x1000
mask == 0x01000000 (== binary 00000001000000000000000000000000)
, the loop will stop on the 24th iteration, andmaskbits
will be 8看一下按位运算符,特别是左移。
http://en.wikipedia.org/wiki/Bitwise_operation#Shifts_in_C。 2C_C.2B.2B_and_Java
Have a look at bitwise operators, specifically left shift.
http://en.wikipedia.org/wiki/Bitwise_operation#Shifts_in_C.2C_C.2B.2B_and_Java
要查看发生了什么:运行它。
http://ideone.com/eB8Kp
To see what's happening: run it.
http://ideone.com/eB8Kp