Fixed-Width Integers
The `fixedint` library provides simple fixed-width integers in Python, allowing for both signed and unsigned types with configurable bit widths. It offers arithmetic and bitwise operations that mimic low-level hardware integer behavior, including silent wrap-around on overflow/underflow. The current version is 0.2.0, and it has a stable but low-cadence release cycle.
Warnings
- gotcha Arithmetic operations (addition, subtraction, multiplication) on `fixedint` types silently wrap around on overflow or underflow, behaving like modulo arithmetic. This is by design but differs significantly from Python's default arbitrary-precision integer behavior.
- gotcha Attempting arithmetic operations between different `fixedint` types (e.g., `UInt16` and `Int32`) will raise a `TypeError`. Types must match for direct arithmetic.
- gotcha Initializing a `fixedint` type with a Python integer value that exceeds its defined bit width (or signed/unsigned range) will raise a `ValueError`.
Install
-
pip install fixedint
Imports
- UInt16
from fixedint import UInt16
- Int32
from fixedint import Int32
- UInt64
from fixedint import UInt64
Quickstart
from fixedint import UInt16, Int32
# Unsigned 16-bit integer
x = UInt16(65535)
print(f"UInt16 max value: {x}")
# Signed 32-bit integer
y = Int32(-1)
print(f"Int32 value: {y}")
# Arithmetic operations (demonstrates wrap-around on overflow)
a = UInt16(65530)
b = UInt16(10)
c = a + b # This will overflow UInt16 (65530 + 10 = 65540)
print(f"65530 + 10 = {c} (wraps around)") # Expected: 4
# Bitwise operations
g = UInt16(0b1010)
h = UInt16(0b0101)
i = g | h
print(f"0b1010 | 0b0101 = {i}") # Expected: 0b1111 (15)
try:
# Instantiation with out-of-range value raises ValueError
j = UInt16(70000)
except ValueError as e:
print(f"Error creating UInt16 with too large value: {e}")