Python contains built-in numeric data types as int(integers), float, and complex. Compared to C programming, Python does not have signed and unsigned integers as data types. There is no need to specify the data types for variables in python as the interpreter itself predicts the variable data type based on the value assigned to that variable. The int data type in python simply the same as the signed integer. A signed integer is a 32-bit integer in the range of -(2^31) = -2147483648 to (2^31) – 1=2147483647 which contains positive or negative numbers. It is represented in two’s complement notation. An unsigned integer is a 32-bit non-negative integer(0 or positive numbers) in the range of 0 to 2^32-1. So, in this article let us know how to convert signed integer to unsigned integer in python.
Example 1: Add 2^32(or 1 << 32) to a signed integer to convert it to an unsigned integer
Python3
signed_integer = - 100 # Adding 2^32 to convert signed to unsigned integer unsigned_integer = signed_integer + 2 * * 32 print (unsigned_integer) print ( type (unsigned_integer)) |
Output:
4294967196 <class 'int'>
Example 2: Using Bitwise left shift(<<) operator
Bitwise left shift: It performs bit manipulation by shifting the left operand bits of the number to the left and fills 0 on voids left as a result.
For example, x << y
Left shifts the integer ‘x’ with ‘y’ integer by y places. It is the same as multiplying x with 2 raised to the power of y(2**y).
Python3
signed_integer = - 1 # Adding 1<<32 to convert signed to # unsigned integer unsigned_integer = signed_integer + ( 1 << 32 ) print (unsigned_integer) |
Output:
4294967295
Example 3:
Python3
signed_integer = - 10 # Adding 1<<32 to convert signed to # unsigned integer unsigned_integer = signed_integer + ( 1 << 32 ) print (unsigned_integer) |
Output:
4294967286