Netmasks and Snow
Posted 06 Jan, 2005 at 09:35 by brent in /Math | Permanent link
I came up with what I think is a simple way to determine if a netmask is valid. If the netmask is represented as an unsigned 4 byte integer, let's call it nm, then if ((~nm) + 1) & (~nm) == 0 then nm is a valid netmask. Just to go in a bit of detail, a valid netmask is a set of 1's followed by a set of zeroes. so if a bit sequence of 01 appears in the netmask, the netmask is invalid.
So ~ is the bitwise complement, + is the standard integer add, and & is bitwise AND. So if the netmask is valid, ~ will flip the bits so it's a sequence of zeroes followed by a sequence of ones. Add one to that and you flip the bits again for all the ones to zeroes and the first zero to a one (or overflow the 4 bytes resulting in a zero value). If the netmask is valid, if you bitwise and that value now with the bitwise complement, you should now get zero.
If the netmask is invalid on the otherhand, then there is a 01 sequence somewhere. When you bit flip you get 10. When you add 1, that zero ensures the 1 is still there (no carry will get it to zero). So when you bitwise AND it with the bitwise complement, you will get 10 in that location which is certainly non-zero.
And it is currently snowing outside, so it looks like I'll have to wear shoes today (snow in sandals just doesn't work).