0
0
Cprogramming~30 mins

Bit manipulation techniques - Mini Project: Build & Apply

Choose your learning style9 modes available
Bit manipulation techniques
📖 Scenario: You are working with a simple embedded system that controls lights. Each light is represented by a bit in an integer variable. You want to learn how to turn lights on and off using bit manipulation.
🎯 Goal: Build a small C program that uses bit manipulation to turn on, turn off, and check the status of specific lights represented by bits in an integer.
📋 What You'll Learn
Create an integer variable called lights with initial value 0
Create an integer variable called light_to_control with value 2
Use bitwise OR to turn on the light at position light_to_control in lights
Use bitwise AND with NOT to turn off the light at position light_to_control in lights
Use bitwise AND to check if the light at position light_to_control is on
Print the status of lights after each operation
💡 Why This Matters
🌍 Real World
Bit manipulation is used in embedded systems, device drivers, and performance-critical code to control hardware or flags efficiently.
💼 Career
Understanding bit manipulation helps in jobs involving low-level programming, embedded software, and systems programming.
Progress0 / 4 steps
1
Create the initial lights variable
Create an integer variable called lights and set it to 0 to represent all lights off.
C
Need a hint?

Use int lights = 0; to start with all lights off.

2
Set the light to control
Create an integer variable called light_to_control and set it to 2 to represent the third light (bit position 2).
C
Need a hint?

Remember bit positions start at 0, so 2 means the third light.

3
Turn on the light using bitwise OR
Use bitwise OR to turn on the light at position light_to_control in lights. Write the code: lights = lights | (1 << light_to_control);
C
Need a hint?

Use 1 << light_to_control to create a mask for the bit to turn on.

4
Turn off the light and check status
Turn off the light at position light_to_control using bitwise AND with NOT: lights = lights & ~(1 << light_to_control); Then check if the light is on using bitwise AND and print "Light is on" or "Light is off" accordingly.
C
Need a hint?

Use ~(1 << light_to_control) to create a mask to turn off the bit.

Use if (lights & (1 << light_to_control)) to check if the bit is on.