Question

I am learning about left shift operators and for multiplying a number with 10 I am using this code.

long int num=a<<3+a<<1;

so that no. a first multiplies with 8 and then with 2 and on adding gets a*10 which is stored in num.

But its giving some strange result like for 5 its 2560, for 6 its 6144.

Can anyone please explain whats wrong in that implementation?

Was it helpful?

Solution 2

The format you are using actually goes this way..

num=a<<(3+a)<<1;

make some difference between the two application of shift operators by using parenthesis like

num=(a<<3)+(a<<1);

OTHER TIPS

You have a problem with precedence - the order operators are performed. + binds more tightly than <<, so:

a<<3+a<<1

actually means: a << (a+3) << 1

for 5 that is 5 << 8 << 1 which is 2560 :)

You need: (a<<3) + (a<<1)

See: http://www.swansontec.com/sopc.html for clarification.

What about warning: suggest parentheses around ‘+’ inside ‘<<’

+ is processed before <<.

Use (a<<3)+(a<<1)

<< operator has less precedence than + operator (Thumb rule Unary Arthematic Relational Logical )

so use braces

     int num = (a<<3) + (a<<1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top