正数和负数的比特运算符 [英] Bitwise Operator on positive and negative numbers

查看:189
本文介绍了正数和负数的比特运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    -5 / 2 = -2

    -5 >> 1 = -3

我从老师那里学到了>> 1把数字除以2。对正数,但它不工作负数。有人可以向我解释吗

I learn from my teacher that >>1 divides the number by 2. It works on positive number but it does not work on negative numbers. Can someone explain to me??

感谢

推荐答案

&神秘状态,对负数使用位移运算符是实现定义的。

这是因为C不区分逻辑和算术位移位。

(算术垫与最高有效位,逻辑pad为0)

对于正数这不重要,对于算术和逻辑位移位都会保持最高有效位为0:

算术5 >> 1

0000 0000 0000 0101 = 5



0000 0000 0000 0010 = 2

As BЈовић & mystical states, using bit shift operators on negative numbers is implementation defined.
The reason for this is C doesn't distinguish between logical and arithmetic bit shifting.
(Arithmetic pads with the most significant bit, logical pads with 0's)
for positive numbers this doesn't matter, for both arithmetic and logical bit shifts would keep the most significant bit as a 0:
Arithmetic 5>>1
0000 0000 0000 0101 = 5
to
0000 0000 0000 0010 = 2

逻辑5 >> 1

0000 0000 0000 0101 = 5

to

0000 0000 0000 0010 = 2

Logical 5>>1
0000 0000 0000 0101 = 5
to
0000 0000 0000 0010 = 2

但是使用负数(2的comp)

算术-5 >> 1

1111 1111 1111 1011 = -5



1111 1111 1111 1101 = -3

however with a negative number (2's comp)
Arithmetic -5>>1
1111 1111 1111 1011 = -5
to
1111 1111 1111 1101 = -3

逻辑-5 >> 1

1111 1111 1111 1011 = -5

至< br>
0111 1111 1111 1101 = 32,765

Logical -5>>1
1111 1111 1111 1011 = -5
to
0111 1111 1111 1101 = 32,765

或至少,这是我的理解

这篇关于正数和负数的比特运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆