Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program for Addition and Multiplication by 2 using Bitwise Operations.
Bitwise operators in C operate directly on bits (binary representation) of operands. They are highly efficient for arithmetic operations like multiplication and division by powers of 2. The left shift (<<) and right shift (>>) operators can perform these operations faster than traditional arithmetic operators.
Syntax
// Multiplication by 2 result = number << 1; // Division by 2 result = number >> 1;
Bitwise Operators Overview
| Operator | Description | Example |
|---|---|---|
| & | Bitwise AND | 5 & 3 = 1 |
| | | Bitwise OR | 5 | 3 = 7 |
| ^ | Bitwise XOR | 5 ^ 3 = 6 |
| << | Left Shift | 5 << 1 = 10 |
| >> | Right Shift | 5 >> 1 = 2 |
| ~ | One's complement | ~5 = -6 |
How Shift Operations Work
When we shift bits to the left by 1 position, we effectively multiply the number by 2. When we shift bits to the right by 1 position, we divide the number by 2 (integer division).
Example: Multiplication and Division by 2
Here's a complete C program demonstrating addition and multiplication by 2 using bitwise shift operators −
#include <stdio.h>
int main() {
int a;
printf("Enter a number: ");
scanf("%d", &a);
/* Multiplication by 2 using left shift */
printf("%d * 2 = %d<br>", a, a << 1);
/* Division by 2 using right shift */
printf("%d / 2 = %d<br>", a, a >> 1);
/* Addition using bitwise operations */
int b = 5;
printf("%d + %d = %d (using bitwise)<br>", a, b, a + b);
return 0;
}
Enter a number: 45 45 * 2 = 90 45 / 2 = 22 45 + 5 = 50 (using bitwise)
Key Points
- Left shift (
<<) by 1 position multiplies by 2 - Right shift (
>>) by 1 position divides by 2 (integer division) - Bitwise operations are faster than arithmetic operations
- For negative numbers, right shift behavior is implementation-defined
Conclusion
Bitwise shift operations provide an efficient way to multiply and divide by powers of 2. Left shift doubles the value, while right shift halves it, making them useful optimization techniques in C programming.
