Discussion: Teeny Tiny Math
Understand how to use bit shift operators in C to multiply and divide integers by powers of two. Learn the mathematical effects of left and right shifts, how bits are moved, and the caveats such as rounding errors and undefined behavior with negative values. Discover how stacking shifts enables more complex operations like multiplying by ten. This lesson deepens your grasp of low-level data manipulation and bitwise operations essential for efficient C programming.
Run the code
Now, it's time to execute the code and observe the output.
#include <stdio.h>
int main()
{
int a;
printf("Enter an integer: ");
scanf("%d", &a);
printf("%d\n", a<<1);
printf("%d\n", a>>1);
return(0);
}Understanding the output
The bit shift operators manipulate the value input, first doubling it and then halving it.
Enter an integer: 8164
When 8 is input, the first value output is double, 16. The second value output is halved, 4. Odd values divided by two are rounded to the next integer.
Explanation
C is often considered a mid-level language—and it has the bitwise operators to prove it. Two of my favorites are the shift operators, << and >>. These tools manipulate data at the bit level, marching bits to the left or right (respectively), which has a mathematical effect on the integer value.
Shift-left operator
The shift-left (<<) operator increases an integer’s value by powers of two, based on the shift value.
Example 1
For example, <<1 shifts the bits left one notch, multiplying the value by two:
0110 0001 (97)
Becomes:
1100 0010 (194)
Example 2
Using <<2 shifts the bits over two spots, multiplying the value by four or