Bitwise operation facts for kids
In computer programming, imagine numbers are made of tiny switches that can be either ON (1) or OFF (0). These ON/OFF switches are called bits. A bitwise operation is a special way to work with numbers by looking at each individual bit. It's like taking apart a number to change its smallest pieces.
Contents
What are Bits?
Computers understand information using only two states: 0 and 1. Each 0 or 1 is called a bit. When you put many bits together, they form a number. For example, the number 5 can be written as 0101 in bits. We count the position of bits from the right side, moving left. So, in 0001 (which is the number 1), the '1' is at the first position (the rightmost one).
Types of Bitwise Operations
There are several types of bitwise operations, each doing something different with the bits.
Bitwise NOT (Complement)
The bitwise NOT operation flips every bit. If a bit is 0, it becomes 1. If it's 1, it becomes 0. It's like turning all the ON switches OFF and all the OFF switches ON.
For example:
- NOT 0111 (which is the number 7)
* Becomes 1000 (which is the number 8)
Another example:
- NOT 10101011 (which is 171)
* Becomes 01010100 (which is 84)
Bitwise AND
The bitwise AND operation compares two numbers, bit by bit. For each pair of bits, if both bits are 1, the result for that position is 1. Otherwise, the result is 0. Think of it like this: if switch A is ON and switch B is ON, then the new switch is ON.
For example:
- 0101 (which is 5)
- AND 0011 (which is 3)
- = 0001 (which is 1)
Let's break down 0101 AND 0011:
- Rightmost bit: 1 AND 1 = 1
- Second from right: 0 AND 1 = 0
- Third from right: 1 AND 0 = 0
- Leftmost bit: 0 AND 0 = 0
- Result: 0001
Bitwise OR
The bitwise OR operation also compares two numbers, bit by bit. For each pair of bits, if either bit is 1 (or both are 1), the result for that position is 1. The only time the result is 0 is if both bits are 0. Think of it like this: if switch A is ON or switch B is ON (or both), then the new switch is ON.
For example:
- 0101 (which is 5)
- OR 0011 (which is 3)
- = 0111 (which is 7)
Let's break down 0101 OR 0011:
- Rightmost bit: 1 OR 1 = 1
- Second from right: 0 OR 1 = 1
- Third from right: 1 OR 0 = 1
- Leftmost bit: 0 OR 0 = 0
- Result: 0111
Bitwise XOR (Exclusive OR)
The bitwise XOR operation (short for "exclusive OR") compares two numbers, bit by bit. For each pair of bits, the result is 1 only if the bits are different (one is 0 and the other is 1). If both bits are the same (both 0 or both 1), the result is 0.
For example:
- 0101 (which is 5)
- XOR 0011 (which is 3)
- = 0110 (which is 6)
Let's break down 0101 XOR 0011:
- Rightmost bit: 1 XOR 1 = 0 (they are the same)
- Second from right: 0 XOR 1 = 1 (they are different)
- Third from right: 1 XOR 0 = 1 (they are different)
- Leftmost bit: 0 XOR 0 = 0 (they are the same)
- Result: 0110
See also
In Spanish: Operador a nivel de bits para niños