How to convert signed to unsigned integer in python
Assuming:
- You have 2's-complement representations in mind; and,
- By
(unsigned long)
you mean unsigned 32-bit integer,
then you just need to add 2**32 (or 1 << 32)
to the negative value.
For example, apply this to -1:
>>> -1
-1
>>> _ + 2**32
4294967295L
>>> bin(_)
'0b11111111111111111111111111111111'
Assumption #1 means you want -1 to be viewed as a solid string of 1 bits, and assumption #2 means you want 32 of them.
Nobody but you can say what your hidden assumptions are, though. If, for example, you have 1's-complement representations in mind, then you need to apply the ~
prefix operator instead. Python integers work hard to give the illusion of using an infinitely wide 2's complement representation (like regular 2's complement, but with an infinite number of "sign bits").
And to duplicate what the platform C compiler does, you can use the ctypes
module:
>>> import ctypes
>>> ctypes.c_ulong(-1) # stuff Python's -1 into a C unsigned long
c_ulong(4294967295L)
>>> _.value
4294967295L
C's unsigned long
happens to be 4 bytes on the box that ran this sample.
How to convert signed 32-bit int to unsigned 32-bit int?
Not sure if it's "nicer" or not...
import ctypes
def int32_to_uint32(i):
return ctypes.c_uint32(i).value
Getting conversion from signed integer to unsigned integer in Python
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
Convert signed to unsigned integer mathematically
Mathematically, the conversion from signed to unsigned works as follows: (1) do the integer division of the signed integer by 1 + max
, (2) codify the signed integer as the non-negative remainder of the division. Here max
is the maximum integer you can write with the available number of bits, 16 in your case.
Recall that the non-negative remainder is the only integer r
that satisfies
1. s = q(1+max) + r
2. 0 <= r < 1+max.
Note that when s >= 0
, the non-negative remainder is s
itself (you cannot codify integers greater than max
). Therefore, there is actually something to do only when s < 0
:
if s >= 0 then return s else return 1 + max + s
because the value r = 1 + max + s
satisfies conditions 1 and 2 above for the non-negative reminder.
For this convention to work as expected the signed s
must satisfy
- (1 + max)/2 <= s < (1 + max)/2
In your case, given that you have 16 bits, we have max = 0xFFFF
and 1 + max = 0x10000 = 65536.
Note also that if you codify a negative integer with this convention, the result will have its highest bit on, i.e., equal to 1. This way, the highest bit becomes a flag that tells whether the number is negative or positive.
Examples:
2 -> 2
1 -> 1
0 -> 0
-1 -> 0xFFFF
-2 -> 0xFFFE
-3 -> 0xFFFD
...
-15 -> 0xFFF1
...
-32768 -> 0x8000 = 32768 (!)
-32769 -> error: cannot codify using only 16 bits.
Cast a 10 bit unsigned integer to a signed integer in python
Naivest possible solution:
def convert(x):
if x >= 512:
x -= 1024
return x
Related Topics
Use Cumcount on Pandas Dataframe With a Conditional Increment
Image.Open() Cannot Identify Image File - Python
How to Save a Numpy Array as a 16-Bit Image Using "Normal" (Enthought) Python
How to Extract the Entire Row and Columns When Condition Met in Numpy Array
How to Write Python Array (Data = []) to Excel
Grab a Number After a String in a File
Index 0 Is Out of Bounds for Axis 0 With Size 0
Find the Last Row from a CSV Input Python
Python Json Add Key-Value Pair
Turn String into a List and Remove Carriage Returns (Python)
Change Date Formats in CSV With Python 3
How to Save Plotly Offline Graph in Format Png
Matching Text Between a Pair of Single Quotes
How to Rotate Xticks on One Axis of Figure in Matplotlib Without "Getting" the Labels as a List