# What is the Logic of AND and OR operations in subnetting?

To calculate subnetting for given IP address and the subnet address, we do AND operation first to get the network address and the first usable IP address of the subnet. Why do we use AND? I know it gives us a viable answer like such as OR or XOR wouldn't give us answers. But why?

Also, to calculate the last usable address in subnet, we invert the subnet first then use OR operation on it. What is the mathematical logic behind this?

I have been calculating subnets for months. But I have never learnt why do we use AND and OR operations in subnetting. I will teach subnetting today but I have realized I have no answer if they ask me WHY about it. I am also kinda ashamed I never asked these before.

Why do we use AND?

Simply put, AND is the boolean operator that yields the result we need. The binary AND operator allows the masking of bits that you want out of the way: `1` in the mask means 'keep', `0` means 'clear'. If you look at AND's logic table, the result is the first operand when the second operand is `1`, and it's always `0` when the second operand is `0`.

That way, the subnet mask extracts the network prefix from an IP address with a known (or presumed) mask in a simple way. You clear all host bits and are left with the network bits = the subnet prefix.

E.g. `192.168.12.34/24` = `192.168.12.34/255.255.255.0` produces the `192.168.12.0/24` prefix. Or `192.168.12.34/21` = `192.168.12.34/255.255.248.0`indicates the `192.168.8.0/21` subnet prefix.

Also, to calculate the last usable address in subnet, we invert the subnet first then use OR operation on it.

Likewise, OR is the operation of choice of you want to set all host bits - for the very last address in a subnet or the directed broadcast address for IPv4. You invert the network mask, so that all mask bits in the host part are `1` and all mask bits in the network part are `0`. OR the mask with the prefix or any address from the subnet and you get the last address in a simple operation.

Of course, there are a number of other ways to get those results, but these are the simplest ones.