这是 C++ 中的代码:
void sign_extending(int x)
{
int r; // resulting sign extended number goes here
struct {signed int x:5 ;} s;
r = s.x = x;
cout << r;
}
void Run()
{
int x=29; // this 29 is -3 ( 11101 ) in 5 bits
// convert this from using 5 bits to a full int
sign_extending(x);
}
此代码的输出为 -3。当我尝试在 python 中重现此代码时,会生成 11101 的位字段,但是当答案转换为 int 时,会给出 29 的答案。
以下是python的代码:
from bitarray import *
def sign_extending(x) :
s = bitarray(5)
r = s = bin(x) #resulting sign extended number goes in r
print (int(r, 2))
x = 29 #this 29 is -3 ( 11101 ) in 5 bits. Convert this from using 5 bits to a full int
sign_extending(x)
我还使用 ctypes 结构作为替代代码,但没有用:
from ctypes import *
def sign_extending(x, b):
class s(Structure):
_fields_ = [("x", c_int, 5)]
r = s.x = x
return r #resulting sign extended number goes in r
x = 29; #this 29 is -3 ( 11101 ) in 5 bits.
r = sign_extending(x, 5) #Convert this from using 5 bits to a full int
print r
我的问题是,我将如何使用位数组或任何其他给出正确答案的方法来产生这个结果。