import ctypes

number = lv & 0xFFFFFFFF

signed_number = ctypes.c_long(number).value
Answer from Raony Barrios on Stack Overflow
🌐
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 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.
Discussions

Unsigned String to Signed Integer?
I would use numpy: import numpy as np print(np.int16("65520")) # -16 More on reddit.com
🌐 r/learnpython
2
3
November 14, 2023
Convert unsigned int to signed int in Python 3
module called ctypes you can also manually do this with something like -1 + 2**32 assuming 32bit More on reddit.com
🌐 r/learnpython
2
1
February 19, 2019
How to convert signed to unsigned integer in python - Stack Overflow
Let's say I have this number i = -6884376. How do I refer to it as to an unsigned variable? Something like (unsigned long)i in C. More on stackoverflow.com
🌐 stackoverflow.com
Need help understanding code for converting unsigned int to signed int
(1 << (32 - 1)) This means take 1, and shift it left 31 times, if you look at the number in a binary way, it'll create the following BINARY number: 100....000 with 31 zeros, that means it'll be the number with the leftmost bit set. doing AND operation with it, will tell us if the left-most bit in id is turned on or not. If it's on, the number should be negative. Also this seems like 32bit unsigned to signed conversion, not 64bit. More on reddit.com
🌐 r/learnpython
3
1
September 9, 2022
🌐
Python documentation
docs.python.org › 3 › library › stdtypes.html
Built-in Types — Python 3.14.3 documentation
February 25, 2026 - The default value for signed is False. The default values can be used to conveniently turn an integer into a single byte object:
🌐
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, ... type of the array elements is the list of the elements of given type_code. Signed Integer is defined by using type_code "i" (small alphabet "i") and it contains negative and posited integers....
🌐
Reddit
reddit.com › r/learnpython › unsigned string to signed integer?
r/learnpython on Reddit: Unsigned String to Signed Integer?
November 14, 2023 -

I have a string (list member) that's being received as 65520, for instance. However this value is being received from a register that's a regular INT 2's complement representation. So really it's -16 in disguise. Obviously that's a problem on the sending side, when it does the INT to ASCII it should just encode it as -16, but it doesn't/can't.

When I read this value into an INT it of course reads the INT as 65520 since it has no way of knowing the original representation. Is there a way to force the ASCII to INT conversion to interpret the string value as a signed INT? So that input string = 65520 outputs INT = -16?

🌐
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 - Signed integers are numerical values that can represent both positive and negative numbers. In Python, signed integers are typically stored using the Two's Complement representation.
🌐
Readthedocs
iec104-python.readthedocs.io › latest › python › number › int16.html
Signed Integer (16-bit) — iec104-python 2.2 documentation
c104 python module · Number · Signed Integer (16-bit) View page source · class c104.Int16 · __init__(self, value: int) → None · create a fixed-length integer instance · Parameters: value (int) – the value · Raises: ValueError – cannot convert value to fixed-length integer ·
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › convert unsigned int to signed int in python 3
r/learnpython on Reddit: Convert unsigned int to signed int in Python 3
February 19, 2019 -

I have an integer from the result of binascii.crc32(). In Python 2, this function returned a signed int. However, in Python 3, it has been changed to always return an unsigned int. I am porting a piece of software from 2 to 3, and one of the things it does is calculate the crc and pack it with struct.pack(">l", crc32). This now causes an error as ">l" expects -2147483648 <= number <= 2147483647 but the crc can now exceed the upper limit.

How would I go about converting the crc to a signed value? As I understand Python doesn't have a concept of signed/unsigned, so you can't do signed_int = (int)unsigned_int; like you can in C.

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. As will be explained, the values are still signed integers (or long), but this has little effect on the application.
🌐
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 ...
🌐
Python
mail.python.org › pipermail › tutor › 2004-January › 027693.html
[Tutor] difference between signed integers and unsigned integers
September 5, 2013 - This means unsigned integers can ... signed integers (but only positive values). On 16 bit computers this was significant, since it translates to the difference between a maximum value of ~32,000 or ~65,000. On 32 bit computers its far less signifocant since we get 2 billion or 4 billion. And on 64 bit computers it becomes of academic interest. IN Python we have large ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-get-the-sign-of-an-integer-in-python
How to Get the Sign of an Integer in Python?
March 24, 2023 - We use a basic if-else structure to determine the sign of a number. if number>0 return 1 else if number<0 return -1 else return 0 · In this method, we use a cascaded if-else-if structure to create a decisionmaking point at the point zero in the number line of integers.
🌐
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.
🌐
LabEx
labex.io › tutorials › python-how-to-work-with-signed-binary-numbers-462163
Python - How to work with signed binary numbers
class SignedNumberValidator: @staticmethod def validate_signed_input(value, bit_width=32): """Comprehensive input validation""" try: ## Convert to integer num = int(value) ## Check range based on bit width max_val = 2 ** (bit_width - 1) - 1 min_val = -2 ** (bit_width - 1) if min_val <= num <= max_val: return num else: raise ValueError(f"Number out of {bit_width}-bit signed range") except ValueError as e: print(f"Invalid input: {e}") return None ... By mastering signed binary number techniques in Python, developers can enhance their understanding of low-level numeric representation, improve computational efficiency, and develop more sophisticated algorithms for handling complex numerical operations across various programming domains.
🌐
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 ... Like C there are no signed and unsigned integer data types in Python. The int in Python acts like a signed integer....
🌐
Python
bugs.python.org › issue42853
Issue 42853: `OverflowError: signed integer is greater than maximum` in ssl.py for files larger than 2GB - Python tracker
January 7, 2021 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/87019
🌐
Data-apis
data-apis.org › array-api › 2023.12 › API_specification › data_types.html
Data Types — Python array API standard 2023.12 documentation
Data type objects are used as dtype specifiers in functions and methods (e.g., zeros((2, 3), dtype=float32)), accessible as .dtype attribute on arrays, and used in various casting and introspection functions (e.g., isdtype(x.dtype, 'integral')).