Reputation: 20620
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?
Upvotes: 0
Views: 1043
Reputation: 4985
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
Upvotes: 1