def add_with_flags(a, b):
"""
Performs 32-bit addition with carry and overflow flag calculation
Simulates ALU addition operation with status flags
"""
# Calculate the sum and mask to 32 bits (simulate 32-bit register)
result = (a + b) & 0xFFFFFFFF
# Carry flag: set when addition exceeds 32-bit unsigned range
carry = 1 if (a + b) > 0xFFFFFFFF else 0
# Extract sign bits (bit 31) for overflow detection
sign_a = (a >> 31) & 1 # Sign bit of operand A
sign_b = (b >> 31) & 1 # Sign bit of operand B
sign_r = (result >> 31) & 1 # Sign bit of result
# Overflow flag: set when signed addition overflows
# Occurs when: same sign inputs produce different sign output
overflow = 1 if (sign_a == sign_b) and (sign_r != sign_a) else 0
return result, carry, overflow
# Test cases demonstrating different flag conditions
tests = [
(0x7FFFFFFF, 0x01), # Max positive + 1 → signed overflow
(0xFFFFFFFF, 0x01), # Max unsigned + 1 → carry (wrap to 0)
(0x80000000, 0x80000000), # Min negative + min negative → signed overflow
(0x12345678, 0x87654321), # Regular addition → no flags
(0x00000000, 0x00000000), # Zero + zero → no flags
]
print("32-bit Addition with Status Flags")
print("=" * 50)
print("Input A + Input B = Result C V")
print("-" * 50)
for a, b in tests:
r, c, v = add_with_flags(a, b)
print(f"{a:#010x} + {b:#010x} = {r:#010x} {c} {v}")
print("\nLegend:")
print("C = Carry flag (unsigned overflow)")
print("V = Overflow flag (signed overflow)")