简体   繁体   中英

Left shift operators in c

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?

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.

怎么warning: suggest parentheses around '+' inside '<<'

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);

+ 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM