I do not understand the following line of C code

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

Can someone explain the following line, I do not understand:

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

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

+4
source share
3 answers

<< - bitwise shift operator to the left ; it shifts the bit of the value remaining by the specified amount. Thus, 1L<<(32-maskbits) shifts the value 1 left 32-maskbits times.

& is a bitwise AND operator .

So, the loop expression mask & (1L<<(32-maskbits)) == 0 checks all bits within the mask value, from lower to higher. The loop will stop at the first (minimum) non-zero mask bit, in which the maskbits point will contain the number of bits higher (and include) this bit.

eg.

  • if mask == 0xFFFF mask == 0xFFFFFFFF (== binary 11111111111111111111111111111111) , the loop will stop at the first iteration, and maskbits will be 32
  • if mask == 0x0001 mask == 0x00000001 (== binary 00000000000000000000000000000001) , the loop will stop at the first iteration again, and maskbits will be 32
  • if mask == 0x1000 mask == 0x01000000 (== binary 00000001000000000000000000000000) , the loop will stop at the 24th iteration, and maskbits will be 8
+6
source

Look at the bitwise operators, in particular the left shift.

http://en.wikipedia.org/wiki/Bitwise_operation#Shifts_in_C.2C_C.2B.2B_and_Java

+1
source

To find out what is going on: run it.

 #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

+1
source

All Articles