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.

🌐
Python documentation
docs.python.org › 3 › library › stdtypes.html
Built-in Types — Python 3.14.3 documentation
1 month ago - Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including hex, octal and binary numbers) yield integers. Numeric literals containing a decimal point or an exponent sign yield floating-point numbers.
🌐
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....
🌐
Python Data Science Handbook
jakevdp.github.io › PythonDataScienceHandbook › 02.01-understanding-data-types.html
Understanding Data Types in Python | Python Data Science Handbook
The standard Python implementation is written in C. This means that every Python object is simply a cleverly-disguised C structure, which contains not only its value, but other information as well. For example, when we define an integer in Python, such as x = 10000, x is not just a "raw" integer.
🌐
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 a two’s-complement signed 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 a sign bit. Passing Py_ASNATIVEBYTES_UNSIGNED_BUFFER will produce the same result as calling PyLong_FromUnsignedNativeBytes().
Find elsewhere
🌐
TechBeamers
techbeamers.com › unsigned-integers-in-python
Enforcing Unsigned Integers in Python - TechBeamers
November 30, 2025 - Python does not have built-in unsigned integers, unlike C, C++, or Java.
🌐
Reddit
reddit.com › r/learnpython › how to maintain an unsignedness of number in python?
r/learnpython on Reddit: How to maintain an unsignedness of number in python?
June 26, 2024 -

How to maintain an unsignedness of number in python?

I have a function that takes an array of octets like so, swaps the bytes, and creates a number out of the array. The solution was seemingly easy with just:

def make_int(octets):
    OCTET_SIZE = 8
    num = 0
    for i in range(len(octets)):
        shift = OCTET_SIZE * i
        num |= octets[i] << shift
    return num

def main():
    octets = [0x00, 0x10, 0xAB, 0xCE]
    four_byte_value = make_int(octets)

But this will occasionally fail and I don't know why. I'll randomly get 0xffffxx and that, to me, is indicative of a twos complement integer. What are potential pitfalls of function that I'm missing that's inducing this strange behavior?

🌐
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.
🌐
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.
🌐
Sololearn
sololearn.com › en › Discuss › 3320064 › python-and-unsigned-int
Python and unsigned int | Sololearn: Learn to code for FREE!
March 12, 2025 - Thanks Brian I was also only concerned about non negative values only. I just assigned as below: a = 0 And expected it to work , but it did not. type(a) is int and as python does not have strong type for unsigned int may be the reason. This made me think about what would happen if I have two api as below in C++. void display(int a); void display(unsigned int); Will above work with swig for python ?
🌐
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.org
discuss.python.org › core development
Conversion between Python and C integers - Core Development - Discussions on Python.org
January 25, 2024 - Python supports integers in unlimited range (if memory is enough), C has several types of integers with limited ranges. There are several ways to convert Python integer to C integer and back: Dedicated C API functions like PyLong_AsLong() and ...
🌐
Chris's Wiki
utcc.utoronto.ca › ~cks › space › blog › python › Unsigned32BitMath
Doing unsigned 32-bit integer math in Python
August 5, 2010 - NumPy also provides signed and unsigned 8 bit, 16 bit, and 64 bit integers under the obvious names. Note that you don't want to mix these types with regular Python integers if you want things to come out just right; you need to make sure that all numbers involved in your code are turned into the appropriate NumPy type.
🌐
Scientific Python
discuss.scientific-python.org › contributor & development discussion
Deprecation of assigning/converting out of bounds Python integers - Contributor & Development Discussion - Scientific Python
November 8, 2022 - I am still a bit on the fence for a deprecation that is currently on NumPy main and scheduled for release with NumPy 1.24. The reason for this change is related to NEP 50, that in the future, I want: np.array(1, dtype=np.int8) + 5000 to raise an error, because this should (approximately) be the same as: np.array(1, dtype=np.int8) + np.int8(5000) While currently the operation returns an int16 result.
🌐
Finxter
blog.finxter.com › 5-best-ways-to-convert-python-bytearray-to-unsigned-int
5 Best Ways to Convert Python bytearray to Unsigned Int – Be on the Right Side of Change
This code snippet creates a byte array and then uses int.from_bytes() to interpret the bytes as a little-endian integer, converting them into an unsigned integer. This method is straightforward and part of the standard Python library.
🌐
Python
docs.python.org › 3 › library › struct.html
struct — Interpret bytes as packed binary data
February 23, 2026 - The IEEE 754 binary16 “half precision” type was introduced in the 2008 revision of the IEEE 754 standard. It has a sign bit, a 5-bit exponent and 11-bit precision (with 10 bits explicitly stored), and can represent numbers between approximately 6.1e-05 and 6.5e+04 at full precision. This type is not widely supported by C compilers: on a typical machine, an unsigned ...
🌐
Real Python
realpython.com › lessons › python-integers
Python Integers (Video) – Real Python
04:06 Just a quick recap before getting into the actual bitwise ops. Python doesn’t have an unsigned integer.
Published   December 7, 2021
🌐
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, ... "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....