Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand the following C code line

I found the following thread:
Calculate broadcast address from ip and subnet mask and there the link to http://lpccomp.bc.ca/netmask/netmask.c

Could someone please explain the following line, I don't understand:

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

especially mask & (1L<<(32-maskbits))

like image 652
mspoerr Avatar asked Feb 26 '23 09:02

mspoerr


2 Answers

<< is the bitwise left shift operator; it shifts the bits of a value left by the given amount. Thus 1L<<(32-maskbits) shifts the value 1 to the left 32-maskbits times.

& is the bitwise AND operator.

So the loop expression mask & (1L<<(32-maskbits)) == 0 tests all the bits within the value of mask, from lower to higher. The loop will stop on the first (lowest) nonzero bit of mask, at which point maskbits will contain the number of bits above (and including) that bit.

E.g.

  • if mask == 0xFFFF mask == 0xFFFFFFFF (== binary 11111111111111111111111111111111), the loop will stop on the first iteration, and maskbits will be 32
  • if mask == 0x0001 mask == 0x00000001 (== binary 00000000000000000000000000000001), the loop will again stop on the first iteration, and maskbits will be 32
  • if mask == 0x1000 mask == 0x01000000 (== binary 00000001000000000000000000000000), the loop will stop on the 24th iteration, and maskbits will be 8
like image 80
Péter Török Avatar answered Mar 06 '23 23:03

Péter Török


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

like image 37
WOPR Avatar answered Mar 06 '23 23:03

WOPR