In looking for a programming function to validate an IP address within a subnet, I had to calculate the subnet mask from a given CIDR bitmask value ie. 192.168.0.0/24, the value 24 in this example.
The first step is to convert the bitmask value (24) into an unsigned 32bit integer. I found this on the internet (specific to our 24 bitmask example): mask = (( 2^24 ) - 1) * ( 2^(32-24) ). This gives me an integer value of 4,294,967,040 which is exactly the binary number I am looking for where the first 24 bits are 1, while the remaining bits are 0 11111111.11111111.11111111.00000000. Obviously, this works for any bitmask value 0-32.
I would like to understand why this works: mask = (( 2^bitmask ) - 1) * (2^( 32-bitmask ))