Assuming:

  1. You have 2's-complement representations in mind; and,
  2. 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.

Answer from Tim Peters on Stack Overflow
Top answer
1 of 7
146

Assuming:

  1. You have 2's-complement representations in mind; and,
  2. 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.

2 of 7
95

To get the value equivalent to your C cast, just bitwise and with the appropriate mask. e.g. if unsigned long is 32 bit:

>>> i = -6884376
>>> i & 0xffffffff
4288082920

or if it is 64 bit:

>>> i & 0xffffffffffffffff
18446744073702667240

Do be aware though that although that gives you the value you would have in C, it is still a signed value, so any subsequent calculations may give a negative result and you'll have to continue to apply the mask to simulate a 32 or 64 bit calculation.

This works because although Python looks like it stores all numbers as sign and magnitude, the bitwise operations are defined as working on two's complement values. C stores integers in twos complement but with a fixed number of bits. Python bitwise operators act on twos complement values but as though they had an infinite number of bits: for positive numbers they extend leftwards to infinity with zeros, but negative numbers extend left with ones. The & operator will change that leftward string of ones into zeros and leave you with just the bits that would have fit into the C value.

Displaying the values in hex may make this clearer (and I rewrote to string of f's as an expression to show we are interested in either 32 or 64 bits):

>>> hex(i)
'-0x690c18'
>>> hex (i & ((1 << 32) - 1))
'0xff96f3e8'
>>> hex (i & ((1 << 64) - 1)
'0xffffffffff96f3e8L'

For a 32 bit value in C, positive numbers go up to 2147483647 (0x7fffffff), and negative numbers have the top bit set going from -1 (0xffffffff) down to -2147483648 (0x80000000). For values that fit entirely in the mask, we can reverse the process in Python by using a smaller mask to remove the sign bit and then subtracting the sign bit:

>>> u = i & ((1 << 32) - 1)
>>> (u & ((1 << 31) - 1)) - (u & (1 << 31))
-6884376

Or for the 64 bit version:

>>> u = 18446744073702667240
>>> (u & ((1 << 63) - 1)) - (u & (1 << 63))
-6884376

This inverse process will leave the value unchanged if the sign bit is 0, but obviously it isn't a true inverse because if you started with a value that wouldn't fit within the mask size then those bits are gone.

🌐
Reddit
reddit.com › r/learnpython › declaring an unsigned integer 16 in python for bit shift operation
r/learnpython on Reddit: Declaring an Unsigned Integer 16 in Python for Bit Shift Operation
October 29, 2023 -

SOLVED: 3 Solutions:

  1. using Numpy : np.uint16()

  2. Using CTypes : ctypes.c_uint16()

  3. Using Bitwise : & 0xFFFF


Hi, I'm trying to convert this code to Python from Go / C. It involves declaring a UInt16 variable and run a bit shift operation. However cant seem to create a variable with this specific type. Need some advise here.

Go Code:

package main

import "fmt"

func main() {

var dx uint16 = 38629

var dy uint16 = dx << 8

fmt.Println(dy) //58624 -> Correct value

}

Python Code:

dx = 38629

dy = (dx << 8)

print(dy) # 9889024 -> not the expected value

print(type(dx)) # <class 'int'>

print(type(dy)) # <class 'int'>

I cant seem to figure out a way to cast or similar function to get this into an Unsigned Int 16.\

Please help.

Discussions

Unsigned integer types in Python API
What does happen? Not implemented Error when using fetchone() and fetchall() after executing SELECT when there is NULL in the tuple (more than 1 element) returned What should happen? Return the cor... More on github.com
🌐 github.com
5
May 22, 2021
cpu architecture - Built in unsigned types in Python - Stack Overflow
What are the design issues driving Python to not support built in unsigned types? I know that in Python an int is an abstraction of an integer value, but why can it not represent the abstraction f... More on stackoverflow.com
🌐 stackoverflow.com
October 11, 2015
[deleted by user]
very very basically, unsigned ints can't represent any number less than 0. As a tradeoff though, the highest number they can represent is almost double the highest number of an equivalently sized signed number. Usually signed ints can store -2,147,483,648 to 2,147,483,647, while unsigned ints can store 0 to 4,294,967,295 All ints (and chars, shorts, longs, long longs and similar), are stored as binary numbers. In the binary format for signed numbers, there is literally a bit that tells you if the number would have a '-' sign written before it. Unsigned numbers don't use this bit for the sign, and instead use it for storing additional information about the number, causing its range of values to double. More on reddit.com
🌐 r/cpp_questions
5
3
September 27, 2021
Is there a shorthand for writing unsigned char or unsigned int ?
If you also know what size integer you want (8, 16, 32, 64 bit), then stdint.h has types like uint8_t, uint16_t, uint32_t, uint64_t that specify both the signedness and size of the integer. Reference here . More on reddit.com
🌐 r/cprogramming
15
7
August 6, 2024
🌐
Python Data Science Handbook
jakevdp.github.io › PythonDataScienceHandbook › 02.01-understanding-data-types.html
Understanding Data Types in Python | Python Data Science Handbook
It's actually a pointer to a compound C structure, which contains several values. Looking through the Python 3.4 source code, we find that the integer (long) type definition effectively looks like this (once the C macros are expanded):
🌐
Sololearn
sololearn.com › en › Discuss › 3320064 › python-and-unsigned-int
Python and unsigned int | Sololearn: Learn to code for FREE!
March 12, 2025 - Basically, I need a mechanism in python to generate unsigned int object ... Though I am unfamiliar with using SWIG, I explored your question with ChatGPT. The primary answer was that it should work as long as you don't try to pass a negative integer. Taking it further, I asked how to make SWIG cast a negative int as unsigned. It gave me the SWIG setup below. I hope this helps: %module example %{ #include "example.h" %} // Custom typemap to convert negative Python integers to their unsigned representation %typemap(in) unsigned int { long temp = PyLong_AsLong($input); if (PyErr_Occurred()) return NULL; // Handle conversion errors $1 = static_cast<unsigned int>(temp); // Proper bitwise conversion } %include "example.h"
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-signed-to-unsigned-integer-in-python
How to convert signed to unsigned integer in Python ? - GeeksforGeeks
April 5, 2021 - A signed integer is a 32-bit integer ... 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....
🌐
Kristrev
kristrev.github.io › programming › 2013 › 06 › 28 › unsigned-integeres-and-python
Unsigned integers and Python
June 28, 2013 - The easiest (and portable!) way to get unsigned integers in Python is to import the required types from the ctypes module. However, sometimes you need to convert Pythons ‘normal’ integers to unsigned values.
🌐
TechBeamers
techbeamers.com › unsigned-integers-in-python
Enforcing Unsigned Integers in Python: A Complete Guide
November 30, 2025 - If you want Python to throw an error whenever an invalid unsigned integer is assigned, use a custom class. class UnsignedInt: """A class to enforce unsigned integers (≥ 0)""" def __init__(self, value: int): if not isinstance(value, int): raise TypeError(f"Expected an integer, received {type(value).__name__}") if value < 0: raise ValueError("Only non-negative values are allowed") self.value = value def __repr__(self): return f"UnsignedInt({self.value})" # ✅ Valid usage x = UnsignedInt(100) print(x) # Output: UnsignedInt(100) # ❌ Throws an error for negative numbers y = UnsignedInt(-5) # ValueError: Only non-negative values are allowed # ❌ Throws an error for non-integer types z = UnsignedInt(10.5) # TypeError: Expected an integer, received float
Find elsewhere
🌐
Python
docs.python.org › 3 › c-api › long.html
Integer Objects — Python 3.14.3 documentation
February 24, 2026 - Create a Python integer from the value contained in the first n_bytes of buffer, interpreted as an unsigned number. flags are as for PyLong_AsNativeBytes(). Passing -1 will select the native endian that CPython was compiled with and assume that the most-significant bit is not a sign bit. Flags other than endian are ignored. Added in version 3.13. ... Macro for creating a Python integer from a process identifier. This can be defined as an alias to PyLong_FromLong() or PyLong_FromLongLong(), depending on the size of the system’s PID type.
🌐
IncludeHelp
includehelp.com › python › signed-and-unsigned-integer-arrays-in-python.aspx
Signed and Unsigned Integer Arrays in Python
May 3, 2025 - To declare an "array" in Python, ... alphabet "i") and it contains negative and posited integers. Unsigned Integer is defined by using type_code "I" (Capital alphabet "I") and it contains only positive integers....
🌐
Readthedocs
mypyc.readthedocs.io › en › latest › int_operations.html
Native integer operations - mypyc 1.20.0+dev.1abbafd4d0edb4ba116995b8aafd3d1556ee3ece documentation
Signed native integer types should only be used if all possible values are small enough for the type. For this reason, the arbitrary-precision int type is recommended for signed values unless the performance of integer operations is critical. Operations on unsigned integers (u8) wrap around on overflow.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-convert-signed-to-unsigned-integer-in-python
How to Convert Signed to Unsigned Integer in Python?
July 24, 2023 - Now that we have covered the first method of converting signed integers to unsigned integers using bitwise operations, let's proceed to the next method. The bitwise left shift operation, denoted by the "<<" symbol in Python, shifts the bits of a number to the left by a specified number of positions.
🌐
Python
docs.python.org › 2.5 › lib › ctypes-fundamental-data-types.html
14.14.2.7 Fundamental data types
December 23, 2008 - The constructor accepts an optional integer initializer; no overflow checking is done. ... Represents the C unsigned int datatype. The constructor accepts an optional integer initializer; no overflow checking is done.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 359675 › signed-and-unsigned-int-in-python
Signed and Unsigned int in python [SOLVED] | DaniWeb
A signed integer just uses one of the bits as a sign, so an 8 bit unsigned can store 0-->255, and an 8 bit signed -127-->127 because one bit is used as a sign. There is bitstring, bitbuffer and bitarray, Also, check PyPi for existing packages whenever you run into a problem like this . ... In Python integers have a size only limited by your computer's memory.
🌐
CodinGame
codingame.com › playgrounds › 54906 › rust-for-python-developers---unsigned-signed-integers-and-casting › unsigned-integer-types
Unsigned Integer Types - Rust for Python Developers
CodinGame is a challenge-based training platform for programmers where you can play with the hottest programming topics. Solve games, code AI bots, learn from your peers, have fun.
🌐
GitHub
github.com › duckdb › duckdb › issues › 1784
Unsigned integer types in Python API · Issue #1784 · duckdb/duckdb
May 22, 2021 - Create a table where col_1 and col_2 are UINTERGER (I'm using UINTEGER in my own project, but I think it also happens in other data types) ... Retrieve a row in python like db.execute('SELECT * FROM table').fetchone() or a column db.execute('SELECT col_2 FROM table').fetchone() where the returned tuples are supposed to be (100, None) and (None, 100)
Published   May 22, 2021
Author   cyvb
🌐
NumPy
numpy.org › doc › stable › user › basics.types.html
Data types — NumPy v2.4 Manual
There are 5 basic numerical types representing booleans (bool), integers (int), unsigned integers (uint) floating point (float) and complex. A basic numerical type name combined with a numeric bitsize defines a concrete type. The bitsize is the number of bits that are needed to represent a ...
🌐
Python documentation
docs.python.org › 3 › library › stdtypes.html
Built-in Types — Python 3.14.3 documentation
1 month ago - All numeric types (except complex) support the following operations (for priorities of the operations, see Operator precedence): ... Also referred to as integer division. For operands of type int, the result has type int. For operands of type float, the result has type float.
🌐
AI_FOR_ALL
kiran-parte.github.io › aiforall › blog-post-4.html
Python 101: DATA TYPES Ⅰ - NUMBERS
April 10, 2021 - You can also write integers in Python using different number systems such as binary (base-2), octal (base-8) or hexadecimal(base-16). ... Like C there are no signed and unsigned integer data types in Python. The int in Python acts like a signed ...