C Arithmetic vs Logical Shift šŸŽÆ

beginner
17 min

C Arithmetic vs Logical Shift šŸŽÆ

Welcome to your C Programming journey where we explore the fascinating world of bit manipulation! Today, we're diving deep into Arithmetic and Logical Shifts, two essential operators that play a significant role in C programming.

What is Shift Operation? šŸ“

Shift operations move the bits of a number to the left or right. This operation is often used for multiplication and division by powers of 2, as well as other bit manipulation tasks.

Arithmetic Shift (<< and >>) šŸ’”

Arithmetic shifts are used when we want to perform mathematical operations on signed integers. During arithmetic shifts, the sign bit (most significant bit) is propagated to fill the vacated bits.

Example: Arithmetic Left Shift (<<)

c
#include <stdio.h> int main() { int num = 10; printf("Number before left shift: %d\n", num); num = num << 2; printf("Number after left shift: %d\n", num); return 0; }

In this example, we left-shift the number 10 by 2 bits. The output will be 40 because in binary form, 10 is 00001010, and after shifting left by 2, we get 00010100.

Example: Arithmetic Right Shift (>>)

c
#include <stdio.h> int main() { int num = 21; printf("Number before right shift: %d\n", num); num = num >> 2; printf("Number after right shift: %d\n", num); return 0; }

In this example, we right-shift the number 21 by 2 bits. The output will be 5 because in binary form, 21 is 00010101, and after shifting right by 2, we get 00001010.

šŸ“ Note: During arithmetic right shift, negative numbers have their sign bit (MSB) set to 1 in order to preserve the original value.

Logical Shift (>>>) šŸ’”

Logical shifts are used when we want to shift unsigned integers. During logical shifts, any vacated bits are filled with zeros.

Example: Logical Right Shift (>>>)

c
#include <stdio.h> int main() { unsigned int num = 21; printf("Number before logical right shift: %d\n", num); num = num >>>; printf("Number after logical right shift: %d\n", num); return 0; }

In this example, we right-shift the number 21 using the logical shift operator (>>>) without the sign extension. The output will be 5 because in binary form, 21 is 00010101, and after shifting right by any number of bits, we get 00001010.

šŸŽÆ Quiz Time!

Quick Quiz
Question 1 of 1

What is the purpose of Arithmetic Shift operations?

By understanding and applying Arithmetic and Logical Shifts, you'll be well on your way to mastering bit manipulation in C programming! 🤩