Computer Science – 4.3 Bit manipulation | e-Consult
4.3 Bit manipulation (1 questions)
To turn on a specific LED using bit manipulation, we need to identify the bit position corresponding to that LED. Since the register is 8-bit, each bit represents one of the LEDs (bit 0 being the least significant bit and bit 7 being the most significant bit).
1. Identify the LED's bit position: Let's say we want to turn on the 3rd LED. This corresponds to bit position 2 (remembering that bit positions are numbered from right to left, starting at 0).
2. Use the bitwise OR operator (|): The bitwise OR operator sets a bit to 1 if either of the corresponding bits in the operands is 1. We can use this to set the desired bit to 1 without affecting the other bits. We create a mask with a 1 only at the desired bit position and then perform a bitwise OR with the register.
The mask for the 3rd LED (bit 2) would be: 00000100 (binary) which is 4 (decimal).
The operation would be: register = register | 4;
This operation will set the 3rd bit of the register to 1, effectively turning on the corresponding LED. All other bits will remain unchanged.
Example: If the initial register value is 00001010 (decimal 10), after performing the operation, the register will become 00001110 (decimal 14). The 3rd bit (counting from the right) has been set to 1.
Reasoning: The bitwise OR operation ensures that the target bit is set to 1, while the other bits are unaffected. This is a non-destructive operation, meaning it doesn't clear or change any other bits in the register.