Hardware Types (hwtypes)
hwtypes is a Python library providing implementations of fixed-size hardware types such as Bit, BitVector, UInt, and SInt. These types are designed to mimic hardware semantics, including explicit bit-widths and modular arithmetic, based on SMT-LIB2 specifications. The current version is 1.4.7, with an active but less frequent release cadence focused on stability and core functionality.
Common errors
-
TypeError: Can't infer bit_width
cause Attempting to create a `BitVector`, `UInt`, or `SInt` instance without explicitly specifying its bit-width.fixSpecify the bit-width using bracket notation: `BitVector[8](value)` or `UInt[16](value)`. -
TypeError: Unsupported operand type(s) for +: 'BitVector[8]' and 'BitVector[16]'
cause Performing an operation between `hwtypes` objects that have different bit-widths.fixEnsure all operands have the same bit-width, or explicitly cast one to match the other's width, e.g., `bv8 + bv16.as_type(BitVector[8])`. -
TypeError: BitVector() takes no arguments
cause Trying to instantiate a hardware type directly like a function call without the bit-width specification.fixUse the indexed type constructor with the desired bit-width, e.g., `BitVector[N](value)` instead of `BitVector(value)`.
Warnings
- gotcha Arithmetic operations on `BitVector` types perform modular (truncating) arithmetic and do not inherently distinguish between signed and unsigned interpretations. For defined signed or unsigned semantics, explicitly use `SInt` or `UInt`.
- gotcha All `BitVector`, `UInt`, and `SInt` types require an explicit bit-width specification during instantiation (e.g., `BitVector[8]`). Operations between types of different bit-widths are typically disallowed and require explicit casting.
- gotcha `hwtypes` objects are immutable. Operations like addition or bitwise logic return new `hwtypes` instances rather than modifying the original object in place. This mirrors hardware behavior.
Install
-
pip install hwtypes
Imports
- Bit
from hwtypes import Bit
- BitVector
from hwtypes import BitVector
- UInt
from hwtypes import UInt
- SInt
from hwtypes import SInt
Quickstart
from hwtypes import Bit, BitVector, UInt, SInt
# Bit
a = Bit(0)
b = Bit(1)
c = a & b # c = Bit(0)
# BitVector (8-bit)
x = BitVector[8](0xAF)
y = BitVector[8](0xBA)
z = x + y # z = BitVector[8](0x69) (modular arithmetic)
# UInt (4-bit unsigned integer)
u = UInt[4](5)
v = UInt[4](3)
w = u + v # w = UInt[4](8)
# SInt (4-bit signed integer)
s = SInt[4](-2)
t = SInt[4](-3)
u_sint = s + t # u_sint = SInt[4](-5)
print(f"Bit c: {c}")
print(f"BitVector z: {z}")
print(f"UInt w: {w}")
print(f"SInt u_sint: {u_sint}")