Home | Projects | Notes > C Programming > Bitwise Operators

Bitwise Operators

 

6 Commonly Used Bitwise Operators in Embedded C Programming

Bitwise Logic Operators

Bitwise Shift Operators

 

Logical Operator vs. Bitwise Operator

Example:

 

Bitwise Logic Operators

In embedded C programs, most of the time you will be doing:

Exercise

Write a program which takes 2 integers from the user, computes bitwise &, |,^ and ~ and prints the result.

Use Case: Testing of Bits

Write a program to find out whether a use entered integer is even or odd. Print an appropriate message on the console. Use testing of bits logic.

Bit masking is a technique in programming used to test or modify the states of the bits of a given data.

Use Case: Setting of Bits

Write a program to set(make bit state to 1) 4th and 7th bit position of a given number and print the result.

Could've done n |= 0x90; instead.

Use Case: Clearing of Bits

Write a program to clear(make bit state to 0) 4th, 5th, 6th bit positions of a given number and print the result.

Alternative 2 ways:

Directly perform bitwise AND

You need to think and calculate the mask value.

Negate the mask value first and then perform bitwise AND

This method could be a shortcut since it it easier to identify the bit pattern to clear and shift it to the proper position. In this case, 111(2) is 7 and we just need to shift 7 to the right 4 places.

Use Case: Toggling of Bits

Rewrite the following code snippet using toggling of bits.

Using bitwise XOR operator ^, above code can be rewritten as:

 

Bitwise Shift Operators

Use Case: Bit Extraction

 

 

References

Nayak, K. (2022). Microcontroller Embedded C Programming: Absolute Beginners [Video file]. Retrieved from https://www.udemy.com/course/microcontroller-embedded-c-programming/