python - cython 中奇怪的整数行为

标签 python c cython

我在 cython 中遇到了一些整数操作的奇怪问题。当我编译这个 cython 代码时......

测试.pyx

from libc.math cimport abs

cdef int c = 2047
cdef int b = 1009
print('%d'%(-(abs(b)&c)))

...像这样

#!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

...我得到 2130706744,但正确答案是 -1009

最佳答案

看起来这可能是 Cython 中的一个错误。 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 添加一个强制转换然后我也得到了正确的答案。

交叉发布到Cython github page

更新:这是对我的 github 问题的回复:

Basically, a signed int is not large enough to hold abs(-MAX_INT-1), so the result was changed to return an unsigned value. On the other hand, I agree that using an unsigned value is quite confusing as well, especially as promotion of equally ranked integers is to the unsigned type so it's contagious. Unclear what the best course of action is here...

关于python - cython 中奇怪的整数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45849744/

相关文章:

python - django.core.exceptions.ImproperlyConfigured : Set the DATABASE_URL environment variable

c++ - 你如何告诉 pyximport 使用 cython --cplus 选项?

python - 什么样的对象可以作为 Spark RDD 中的元素?

命名元组的 Python 语法

python - 使用Django @ csrf_exempt,request.session始终为空

python - 在 Cython 中使用 regex.h C 库

c - C/Cython 中的动态类型转换

C 程序给出了不同的答案,其中包含一个 float 的 rand() 调用

c++ - 创建一个自定义的lightdm迎宾器

C编程: End of file - operation