DeaD_EyE

set or clear a bit without branching

Feb 17th, 2026
8,870
0
Never
3
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.28 KB | None | 0 0
  1. def set_bit(data: int, bit: int, value: bool):
  2.     """
  3.    Set or clear a bit of given data and return it.
  4.    Look here: https://graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching
  5.    """
  6.     data ^= (-value ^ data) & (1 << bit)
  7.     return data
  8.  
Advertisement