Vid - 1 year ago 141

C Question

I there any way to check that 32 bit netmask is valid or not using bitwise operator?

I have to check from msb side that '1' are in continuous stream or not.

eg 11111111.0.0.0 (255.0.0.0)is valid

but 11111101.0.0.0 (253.0.0.0) is not.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

First thing to do is to check for the netmask being non zero (a nasty edge case). Given this is ok, you need to take the bitwise inverse.

```
uint32_t y = ~x;
```

Then add one

```
uint32_t z = y + 1;
```

Then if `x`

was a proper netmask, there will be at most 1 bit set in this.

To test that, simply and `z`

with `z - 1`

, which happens to be `y`

. The result will be zero if all is OK, non zero otherwise.

```
valid = (z & y) == 0;
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**