the program below computes the value of this expression below
m = i /16 + j *128-17 + k *2- l /32 , if i > j + 2 * k else
m = i /16 + j *128-17 + k *2 + l /32
the person who wrote this program did not use multiplication and division operators,may somebody explain to me whats really going on here,i mean where are the( * and /) in the program?why or what is the purpose of the shifting right and left?
#include <stdio.h>
#include <cstdlib>
int main(){
unsigned int i, j, k, l, m;
printf("i = "); scanf("%d", &i);
printf("j = "); scanf("%d", &j);
printf("k = "); scanf("%d", &k);
printf("l = "); scanf("%d", &l);
if (i > j + (k << 1))
m = (i >> 4) + (j << 7) - 17 + (k << 1) - (l >> 5);
else
m = (i >> 4) + (j << 7) - 17 + (k << 1) + (l >> 5);
printf("m = %d\n", m);
system("pause");
}
Each digit in a binary number is 2 times the previous digit:
Thus if you shift the bits 1 place to the left in a number it is equivalent to multiplying by 2.
Conversely shifting 1 place to the right is like dividing by 2.
If you shift multiple places you just increase by a power of 2. Thus shifting
nplaces to the left is like multiplying by2^nand shiftingnplaces to the right is like dividing by2^netc.There is absolutely no reason to do this.
In fact I would say it is a terrible and completely bad practice in
normalsituations; the compiler will automatically do this optimization if it thinks it will be a benefit and the downside (as you have noticed) is that it makes the code much harder to read.If you know the compiler is bad and does not do this then maybe it is worth doing (but only maybe).