简体   繁体   English

c中的左移运算符

[英]Left shift operators in c

I am learning about left shift operators and for multiplying a number with 10 I am using this code. 我正在学习左移操作符和数字乘以10我正在使用此代码。

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. 第一个与8相乘,然后与2相乘,在加上得到一个* 10,存储在num中。

But its giving some strange result like for 5 its 2560, for 6 its 6144. 但它给出了一些奇怪的结果,比如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 一个<< 3 + A << 1

actually means: a << (a+3) << 1 实际上意味着:a <<(a + 3)<< 1

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

You need: (a<<3) + (a<<1) 你需要:(a << 3)+(a << 1)

See: http://www.swansontec.com/sopc.html for clarification. 请参阅: http//www.swansontec.com/sopc.html以获得澄清。

怎么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) 使用(a<<3)+(a<<1)

<< operator has less precedence than + operator (Thumb rule Unary Arthematic Relational Logical ) <<运算符的优先级低于+运算符(Thumb rule Unary Arthematic Relational Logical)

so use braces 所以用牙箍

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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