从可变位宽延伸的符号

Sign extending from a variable bit width

本文关键字:符号      更新时间:2023-10-16

这是C++中的一个代码:

#include <iostream>
#include<limits.h>
using namespace std;
void sign_extending(int x,unsigned b)
{
  int r;      // resulting sign-extended number
  int const m = CHAR_BIT * sizeof(x) - b;
  r = (x << m) >> m;
  cout << r;
}
void Run()
{
  unsigned b = 5; // number of bits representing the number in x
  int x = 29;      // sign extend this b-bit number to r
 sign_extending(x,b);
}

结果:-3

生成的数字将是一个有符号的数字,其位数存储在b中。我正试图在python中复制此代码:

from ctypes import *
import os
def sign_extending(x, b):
  m = c_int(os.sysconf('SC_CHAR_BIT') * sizeof(c_int(x)) - b)    
  r = c_int((x << m.value) >> m.value)        # Resulting sign-extended number
  return r.value
b = c_int(5)       # number of bits representing the number in x
x = c_int(29)      # sign extend this b-bit number to r
r = sign_extending(x.value, b.value)
print r

结果:29

我无法像从c++中的输出一样获得符号扩展数。我想知道我当前代码(python(中的错误或问题,以及使用此技术解决问题的可能方案。

您可以使用

def sign_extending(x, b):
    if x&(1<<(b-1)): # is the highest bit (sign) set? (x>>(b-1)) would be faster
        return x-(1<<b) # 2s complement
    return x