├── README.md └── setbit.py /README.md: -------------------------------------------------------------------------------- 1 | # bit 2 | Bit manipulation algorithm operations 3 | This script defines several functions for common bit manipulation operations like setting, clearing, toggling, checking, and updating bits in a binary number. You can use these functions to perform various operations on binary numbers in Python. 4 | -------------------------------------------------------------------------------- /setbit.py: -------------------------------------------------------------------------------- 1 | def set_bit(number, position): 2 | """Set the bit at the given position to 1.""" 3 | return number | (1 << position) 4 | 5 | def clear_bit(number, position): 6 | """Clear the bit at the given position to 0.""" 7 | return number & ~(1 << position) 8 | 9 | def toggle_bit(number, position): 10 | """Toggle the bit at the given position.""" 11 | return number ^ (1 << position) 12 | 13 | def check_bit(number, position): 14 | """Check if the bit at the given position is set (1).""" 15 | return (number >> position) & 1 16 | 17 | def update_bit(number, position, value): 18 | """Update the bit at the given position with the given value (0 or 1).""" 19 | mask = ~(1 << position) 20 | return (number & mask) | (value << position) 21 | 22 | # Example usage 23 | num = 10 # 1010 in binary 24 | 25 | print("Original number:", num) 26 | print("Setting bit at position 2:", set_bit(num, 2)) 27 | print("Clearing bit at position 1:", clear_bit(num, 1)) 28 | print("Toggling bit at position 3:", toggle_bit(num, 3)) 29 | print("Checking bit at position 0:", check_bit(num, 0)) 30 | print("Updating bit at position 1 with 1:", update_bit(num, 1, 1)) 31 | --------------------------------------------------------------------------------