3

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.

Muhammad Ali Qadri
  • 606
  • 2
  • 8
  • 21
  • what you're doing is not sign-extending. In C++ already does that sign extension for you when you use signed integers. – Marcus Müller Aug 06 '16 at 10:44
  • 1
    This question is _extremely_ similar to the one you asked yesterday: http://stackoverflow.com/questions/38794715/bit-field-specialization-in-python – PM 2Ring Aug 06 '16 at 11:18
  • 1
    Also, in C and C++, shifting a negative number right is [not guaranteed to replicate the sign bit](http://stackoverflow.com/questions/6487918/signed-right-shift-which-compiler-use-logical-shift). – Bo Persson Aug 06 '16 at 11:24
  • 1
    @PM2Ring it is similar, however i am trying to do the same thing using a different technique. Yesterday i asked about using bit fields and now I am facing a problem with this method. – Muhammad Ali Qadri Aug 06 '16 at 11:27

1 Answers1

3

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
janbrohl
  • 2,626
  • 1
  • 17
  • 15
  • i can use this but i wanted a solution which was an improvement on my current code and not entirely changing it – Muhammad Ali Qadri Aug 06 '16 at 12:06
  • to me it looks like an improvement because of better readability ;) I cannot actually improve your code, sorry. – janbrohl Aug 06 '16 at 12:26
  • Why would you want to port bad code? People told you that `>>` is not guaranteed to do sign-extension. You should port this code back to C++ instead. – rustyx Aug 06 '16 at 12:59