如题,
《python源码剖析》中第32页,
有个检查加法结果是否溢出的代码,
大致如下:
C/C++ code:
long a, b, x;
x = a + b;
//检查结果是否溢出
if((x^a)>=0 || (x^b)>=0)
return OK; //没有益处?
请教,
为什么上面的两个异或可以判断是否溢出?
谢谢!!
我顶
假定long是32位。x^a的结果是int,也是32位。
首先,x^a>=0,说明x^a的最高位bit31是0,
也就是说,x和a的最高位都是1,或者都是0
假设,
我们用4个bit表示整数。
则能够表示的范围是-7到7;
则(-7)+(-1)= -8应该溢出。
上式的二进制补码是:
1001 + 1111 = 1000;
但这时,
(1001)^(1000)=0001 >= 0
(1111)^(1000)=0111 >= 0
若上式采用补码的计算过程如果正确,
则题目中的检查溢出的方法,还是让我迷惑。
另外,如果不用补码,
则,-1+1=0 的二进制表示就成了1001+0001=1010
还请大家继续指点。
谢谢!!
引用 假定long是32位。x^a的结果是int,也是32位。 首先,x^a>=0,说明x^a的最高位bit31是0, 也就是说,x和a的最高位都是1,或者都是0 引用 假设, 我们用4个bit表示整数。 则能够表示的范围是-7到7; 则(-7)+(-1)= -8应该溢出。
相关问答:
麻烦高手解答一下 谢谢了 我是新手 一些概念都不太清楚。。。 pyodbc is a Python module that allows you to use ODBC to connect to almost any database from Windows, Linux, OS/X, and more. pyodbc是 ......
//下面的代码运行正常 tomstrs=re.findall(......) mtxx='' for tomstr in tomstrs: tomstr=tomstr.strip() if tomstr: mtxx += tomstr ......
如果一段代码 Python code: #!/usr/bin/python2.5 from urllib2 import Request,urlopen,URLError def check(): req = Request('http://www.google.com') try: res = urlopen(req).read() ......
比如 Python code: @orm.validates('title') def validate_title(self, key, title): """Assure that page titles are wikiwords and valid length""" ......