Python中的位域专业化 [英] Bit field specialization in python

查看:151
本文介绍了Python中的位域专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The output of this code is -3. When i try to reproduce this code in python the bit field of 11101 is generated but when the answer is converted to an int the answer of 29 is given .

以下是python代码:

the following is code of 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结构作为备用代码,但不使用:

I also used ctypes structures as an alternative code but no use :

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

我的问题是,我将如何使用位数组或提供正确答案的任何其他方法产生此结果。

My question is that how would i produce this result using bit arrays or any other method that gives the correct answer.

推荐答案

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

In your code s is a class and the class x member actually represents the field type, so assigning s.x = 29 essentially destroys that object and assigns a normal Python int to it. Example:

>>> 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 = sx = 29 不执行 sx = 29 ,然后 r = sx 为在C / C ++中,但实际上 r = 29 sx = 29 。示例:

Also, even if you create an instance first, r = s.x = 29 does not do s.x = 29 then r = s.x as in C/C++ but essentially r=29 and s.x=29. Example:

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

因此要修复,实例化该类并分配 sx = 29 并返回:

So to fix, instantiate the class, assign s.x = 29 and return it:

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中的位域专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆