...

/

Discussion: Teeny Tiny Math

Discussion: Teeny Tiny Math

Execute the code to understand the output and gain insights into bitwise shift operations.

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);
}
C code for the given puzzle

Understanding the output

The bit shift operators manipulate the value input, first doubling it and then halving it.

Enter an integer: 8
16
4
Code output

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)
Shift-left (<<1) multiplies 0110 0001 (97) by 2

Becomes:

1100 0010 (194)
Shift-left (<<1) results in 1100 0010 (194)
Example 2

Using <<2 shifts the bits over two spots, multiplying the value by four or 222^2 ...