Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two's complement sign extension python?

I'm wondering if there's a way to do a two's complement sign extension as you would in C/C++ in Python, using standard libraries (preferably on a bitarray).

C/C++:

// Example program
#include <iostream>
#include <string>

int main()
{
    int x = 0xFF;
    x <<= (32 - 8);
    x >>= (32 - 8);
    std::cout << x;
    return 0;
}

And here's a Python function I've written which (in my testing) accomplishes the same thing. I'm simply wondering if there's a built-in (or just faster) way of doing it:

def sign_extend(value, bits):
    highest_bit_mask = 1 << (bits - 1)
    remainder = 0
    for i in xrange(bits - 1):
        remainder = (remainder << 1) + 1

    if value & highest_bit_mask == highest_bit_mask:
        value = (value & remainder) - highest_bit_mask
    else:
        value = value & remainder
    return value
like image 736
Vasu Avatar asked Aug 15 '15 23:08

Vasu


1 Answers

The following code delivers the same results as your function, but is a bit shorter. Also, obviously, if you are going to apply this to a lot of data, you can pre-calculate both the masks.

def sign_extend(value, bits):
    sign_bit = 1 << (bits - 1)
    return (value & (sign_bit - 1)) - (value & sign_bit)
like image 102
Patrick Maupin Avatar answered Nov 15 '22 12:11

Patrick Maupin