DeaD_EyE icon

set or clear a bit without branching

DeaD_EyE | PRO | 02/17/26 05:32:29 PM UTC | 0 ⭐ | 13042 👁️ | Never ⏰ | []
Python |

280 B

|

None

|

0 👍

/

0 👎

def set_bit(data: int, bit: int, value: bool):
    """
    Set or clear a bit of given data and return it.
    Look here: https://graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching
    """
    data ^= (-value ^ data) & (1 << bit)
    return data
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎