Skip to content

Instantly share code, notes, and snippets.

@ultrafunkamsterdam
Last active November 28, 2022 13:19
Show Gist options
  • Save ultrafunkamsterdam/7f1f736c22d638daed281101ec752a3a to your computer and use it in GitHub Desktop.
Save ultrafunkamsterdam/7f1f736c22d638daed281101ec752a3a to your computer and use it in GitHub Desktop.
bit replace
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