Last active
November 28, 2022 13:19
-
-
Save ultrafunkamsterdam/7f1f736c22d638daed281101ec752a3a to your computer and use it in GitHub Desktop.
bit replace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def bit_replace(byte:int, pos:int, new_val:int): | |
""" | |
Takes a integer <byte> and changes the bit on <pos> with <new_val> (0 or 1). | |
pos is counted from right to left, so pos 0 = LSB | |
:param byte (int): unsigned int | |
:param pos (int) the binary position to replace. pos is counted from "right" to "left", so pos 0 is LSB | |
:param new_val (int): the new value. either 0 (off) or 1 (on) | |
""" | |
if not 0 <= new_val <= 1: | |
raise ValueError("new_val of %d is not 0 or 1 and can not be used in binary" % new_val) | |
return (byte & ~(1 << pos)) | (new_val << pos) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment