0

First, forgive me my ignorance to ask this kind of question, but I couldn't help as I am not good at Python.

I met following Python code that I need to convert into C++.

def getSignedNumber(number, bitLength):
    mask = pow(2,bitLength) - 1
    if number & (1 << (bitLength - 1)):
        return number | ~mask
    else:
        return number & mask


def getUnsignedNumber(number, bitLength):
    mask = pow(2,bitLength) - 1
    return number & mask

This is used to convert unsigned int into signed int and vice versa. But I don't know why we have to do this because I think just casting to corresponding type would be enough. Maybe it's because Python is a dynamic-type language and needs this kind of operations? Am I missing something here?

1
  • 2
    Python uses arbitrary precision integers so without an explicit conversion like this, unexpected things will happen when dealing with numbers that wouldn't fall within the range of integers that convert properly automatically (0 to 2^31-1). Commented Oct 16, 2012 at 14:34

1 Answer 1

1

do you mean reinterpret_cast or dynamic_cast?

Long story short: you need this for arbitrary bitlength integers. Explanation attempt below:

The getUnsignedNumber interprets a block of memory like an nBit number. This is necessary since you get memory only in certain chunk sizes (usually you can not allocate 3bit, you need to allocate the next larger unit, a byte (char)). Thus you need to make sure you ignore the 5 extra bits you don't need.

getSignedNumber does the same for signed numbers, however here we need to pad with the sign bit if the number is negative. Thus you need this function even for c. (Just Imagine you store -3 In your char and want to read that as an unsigned 3 bit number)

It appears, that this is used for the proper padding of numbers, say you have a char:

c = 10001111

now if you want to interpret this as a four bit signed type, you would actually have to put

c = 11111111

since if a number is negative in twos complement all bits preceeding it are actually one. However if you interpret it as a 5 bit signed type, you see that the sign bit is 0, thus all leading bits should be zero. So you have to mask it so that

c = 00001111

Sign up to request clarification or add additional context in comments.

2 Comments

I use static_cast buddy. As far as I can see, the casting is working fine in C++. Anyway, thanks for your answer.
@Thomas : I just wonder if the code you are porting ever uses incomplete Initialization (allocate char write in 7, interprete char as 3 bit signed), I guess that in this scenario the results would differ.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.