python - python 中的位域特化

标签 python ctypes bit-fields sign-extension

这是 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

我的问题是,如何使用位数组或任何其他给出正确答案的方法产生这个结果。

最佳答案

在您的代码中,s 是一个类,类 x 成员实际上表示字段类型,因此分配 s.x = 29 本质上会破坏该类型对象并为其分配一个普通的 Python int。示例:

>>> from ctypes import *
>>> class S(Structure):
...     _fields_ = [('x',c_int,5)]
... 
>>> S.x
<Field type=c_long, ofs=0:0, bits=5>
>>> S.x = 29
>>> S.x
29

此外,即使您先创建一个实例,r = s.x = 29 也不会执行 s.x = 29 然后 r = s.x 作为在 C/C++ 中,但本质上是 r=29s.x=29。示例:

>>> from ctypes import *
>>> class S(Structure):
...     _fields_ = [('x',c_int,5)]
...     
>>> s=S()
>>> r=s.x=29
>>> s.x
-3
>>> r
29

因此,要修复此问题,请实例化该类,分配 s.x = 29 并返回它:

from ctypes import *
def sign_extending(x, b):
    class S(Structure):
        _fields_ = [("x", c_int, b)]
  s=S()
  s.x = x
  return s.x

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

输出:

-3

关于python - python 中的位域特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38794715/

相关文章:

Python argparse : Is there a way to specify a range in nargs?

python - 如何 "stash"随机状态生成器状态

c++ - 你怎么称呼这个 : "unsigned int a_bit : 1;"? 是否有位域之外的用途?

c - 分配给结构成员的值不正确

python - Cython 在诗歌 sdist tar.gz 中生成了 c/cpp 文件,用于无 cython 安装

python - 如何根据字符串值列表对 Pandas 数据框进行子集化?

python - MEX 相当于 Python(C 包装函数)

python ctypes将指向结构的指针作为参数发送给 native 库

python - 使用ctypes从Python获取C中自定义数据类型的地址

c - C 编译器如何为位域定义的结构分配结构内存?