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.

🌐
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.
🌐
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.

🌐
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 - Python provides a single int type for integers and does not have separate signed and unsigned integer data types.
🌐
TechBeamers
techbeamers.com › unsigned-integers-in-python
Enforcing Unsigned Integers in Python: A Complete Guide
November 30, 2025 - For memory buffers, C-compatible data structures, or embedded systems, Python’s ctypes provides true unsigned integers like uint16_t or uint32_t.
🌐
Sololearn
sololearn.com › en › Discuss › 3320064 › python-and-unsigned-int
Python and unsigned int | Sololearn: Learn to code for FREE!
March 12, 2025 - sl_scroll_/de/Discuss/2848516/how-is-python-used-in-the-ai-artificial-intelligence-fieldPending
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 359675 › signed-and-unsigned-int-in-python
Signed and Unsigned int in python [SOLVED] | DaniWeb
With pysnmp, use the appropriate SMI type, e.g. Unsigned32 for integer scalars or OctetString when the MIB defines an octet string: from pysnmp.proto.rfc1902 import Unsigned32, OctetString val_u32 = Unsigned32(u16) # ensure value is in range, e.g. value & 0xFFFFFFFF val_oct = OctetString(u16_bytes) # if the MIB expects 2-octet data · Avoid string concatenation; in Python text strings are not raw bytes.
Find elsewhere
🌐
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....
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-convert-signed-to-unsigned-integer-in-python
How to Convert Signed to Unsigned Integer in Python?
March 27, 2026 - Converting signed to unsigned integers in Python involves shifting negative values into the positive range using addition or bitwise operations.
🌐
Python
docs.python.org › 3 › c-api › long.html
Integer Objects — Python 3.14.7 documentation
CPython implementation detail: CPython keeps an array of integer objects for all integers between -5 and 256. When you create an int in that range you actually just get back a reference to the existing object. PyObject *PyLong_FromUnsignedLong(unsigned long v)¶
🌐
AI_FOR_ALL
kiran-parte.github.io › aiforall › blog-post-4.html
Python 101: DATA TYPES Ⅰ - NUMBERS
April 10, 2021 - The signed integer can take both positive and negative values, whereas an unsigned integer can take only positive values.
🌐
LiveJournal
planet-python.livejournal.com › 15120301.html
TechBeamers Python: Enforcing Unsigned Integers in Python: A Complete Guide: planet_python — LiveJournal
March 13, 2025 - Python does not have built-in unsigned integers, unlike C, C++, or Java. This can create problems when:✔ You need strictly non-negative values✔ You are porting code from C/C++✔ You work with binary data, memory buffers, or numerical computing ...
🌐
Skillapp
skillapp.co › blog › understanding-unsigned-integers-in-python-a-comprehensive-guide
Understanding Unsigned Integers in Python – A Comprehensive Guide
Additionally, unsigned integers can allow for more efficient memory usage and faster computations, as they require fewer bits to represent the same range of values compared to signed integers. In Python, integers are a built-in data type used to represent whole numbers.
🌐
Real Python
realpython.com › lessons › python-integers
Python Integers (Video) – Real Python
This back-and-forth ensures that bitwise operations do the same thing regardless of the size of the integer. Consistency is good, but of course, that is consistency with two’s complement, which I believe I have mentioned is a bit weird with bitwise operations. 04:06 Just a quick recap before getting into the actual bitwise ops. Python doesn’t have an unsigned integer.
Published: December 7, 2021
🌐
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?

🌐
Readthedocs
mypyc.readthedocs.io › en › latest › int_operations.html
Native integer operations - mypyc 2.4.0+dev.8b3e7d8b9f63543374e53d1c389ea443dd65bc46 documentation
u8 (8-bit unsigned integer) i64, i32, i16 and u8 are native integer types and are available in the mypy_extensions module. int corresponds to the Python int type, but uses a more efficient runtime representation (tagged pointer). Native integer types are value types.
🌐
Stack Exchange
blender.stackexchange.com › questions › 321525 › how-to-create-unsigned-int-property
python - How to create unsigned Int property? - Blender Stack Exchange
July 13, 2024 - bpy.types.Scene.vertInt1 = IntProperty( name="Integer", description="Enter an integer", default = 2, subtype='UNSIGNED') ... $\begingroup$ Python int can accept any size limited by memory as far as I know, so int in [-inf, inf] in documentation for maximum value (docs.blender.org/api/current/bpy.types.IntProperty.html) seems to make sense.
🌐
Bomberbot
bomberbot.com › python › converting-signed-to-unsigned-integers-in-python-a-deep-dive
Converting Signed to Unsigned Integers in Python: A Deep Dive - Bomberbot
In Python, integers are objects of arbitrary precision, meaning they can grow as large as your system's memory allows. This design choice eliminates many of the limitations associated with fixed-width integers, but it also means that Python doesn't have a native unsigned integer type.
🌐
Chris's Wiki
utcc.utoronto.ca › ~cks › space › blog › python › Unsigned32BitMath
Doing unsigned 32-bit integer math in Python
August 5, 2010 - In pure Python for unsigned 32-bit arithmetic, it suffices to mask numbers with 0xffffffffL after every potentially overflowing operation.