我在cython中遇到了一个奇怪的整数操作问题。当我编译这段cython代码时...
test.pyx
from libc.math cimport abs
cdef int c = 2047
cdef int b = 1009
print('%d'%(-(abs(b)&c)))...like this
#!python
from subprocess import check_output
CFLAGS = check_output('python-config --cflags'.split()).decode('utf-8').strip()
LDFLAGS = check_output('python-config --ldflags'.split()).decode('utf-8').strip()
check_output('cython test.pyx'.split())
compile_call = ('clang -c test.c %s'%(CFLAGS)).split()
check_output(compile_call)
link_call = ('clang test.o -o test.so -shared %s'%(LDFLAGS)).split()
check_output(link_call)
import test...I获取2130706744,但正确答案是-1009。
发布于 2017-08-24 06:02:30
看起来这可能是Cython中的一个bug。test.c中的相关行是
__pyx_t_2 = __Pyx_PyInt_From_unsigned_int((-(__pyx_t_1 & __pyx_v_4test_c)));清楚地将我们的数字解释为无符号会给出一个错误的答案。但是,如果我删除abs调用,那么我会得到
__pyx_t_1 = __Pyx_PyInt_From_int((-(__pyx_v_4test_b & __pyx_v_4test_c)));结果是正确的。如果我像print('%d'%(-(<int>abs(b)&c)))一样向int添加一个类型转换,那么我也会得到正确的答案。
Cross发布到Cython github page
更新:是对我的github问题的回应:
基本上,带符号的整数不足以容纳abs(-MAX_ int -1),因此结果被更改为返回一个无符号值。另一方面,我同意使用无符号值也是非常令人困惑的,特别是由于相同排名的整数的提升是无符号类型的,所以它是有传染性的。不清楚这里的最佳行动方案是什么……
https://stackoverflow.com/questions/45849744
复制相似问题