Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sign extending from a variable bit width

Here is a code in 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);
}

Result : -3

The resulting number will be a signed number with its number of bits stored in b. I am trying to replicate this code in 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

Result : 29

I cannot get the sign extended number just like from the output in c++. I would like to know the error or problems in my current code(python) and also a possible solution to the issue using this technique.

like image 481
Muhammad Ali Qadri Avatar asked Sep 02 '26 14:09

Muhammad Ali Qadri


1 Answers

you can use

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
like image 83
janbrohl Avatar answered Sep 04 '26 02:09

janbrohl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!