How to do bitwise complement on a 16-bit signal using Python?

If you want to get an inversion of only the first 16 bits of a number, you can take an XOR of that number with 65535 (which is 16 ones in binary: 0b1111111111111111).

Understanding 16-bit Complement

The bitwise complement flips all bits in a binary number. For a 16-bit signal, we need to flip only the lower 16 bits while preserving the original bit pattern within that range.

Original (3): 0000000000000011 XOR with 65535: 1111111111111111 Result: 1111111111111100 Bit positions: 15 14 13 ... 2 1 0 65535 = 2ยน? - 1

Example

a = 3  # 11 in binary
b = a ^ 65535
print("Original number:", a)
print("Binary of original:", bin(a))
print("16-bit complement:", b)
print("Binary of result:", bin(b))
Original number: 3
Binary of original: 0b11
16-bit complement: 65532
Binary of result: 0b1111111111111100

Using Hexadecimal Notation

You can also use hexadecimal notation for better readability ?

a = 0x00FF  # 255 in decimal
mask = 0xFFFF  # 65535 in decimal (16-bit mask)
result = a ^ mask

print(f"Original: 0x{a:04X} ({a})")
print(f"Mask: 0x{mask:04X} ({mask})")
print(f"Result: 0x{result:04X} ({result})")
print(f"Binary: {bin(result)}")
Original: 0x00FF (255)
Mask: 0xFFFF (65535)
Result: 0xFF00 (65280)
Binary: 0b1111111100000000

Function Implementation

Here's a reusable function for 16-bit complement ?

def complement_16bit(number):
    """Return 16-bit complement of a number."""
    return number ^ 0xFFFF

# Test with different values
test_values = [0, 1, 255, 1000, 32767]

for value in test_values:
    complement = complement_16bit(value)
    print(f"{value:5d} -> {complement:5d} (0x{complement:04X})")
    0 -> 65535 (0xFFFF)
    1 -> 65534 (0xFFFE)
  255 -> 65280 (0xFF00)
 1000 -> 64535 (0xFBF7)
32767 -> 32768 (0x8000)

Key Points

Concept Value Description
16-bit mask 65535 Binary: 1111111111111111
Hexadecimal 0xFFFF More readable notation
Operation XOR (^) Flips bits where mask is 1

Conclusion

Use XOR with 65535 (0xFFFF) to perform 16-bit complement operations. This technique is commonly used in digital signal processing and embedded systems programming.

Updated on: 2026-03-24T20:34:15+05:30

384 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements