'Set allocated bit value in a byte python

Suppose there's a 1 byte like this.

header = b'\xc1' #0b11000001

I expect there a function like this.

def set_bit_val(byte,bits,val,shift):
   return new_byte

header = set_bit_val(header,3,2,4) #0b10100001

So how that function work is.

  • allocated bit, in this case is 3 bits.
  • set value, in this case is 2, since we allocated 3 bits so the val is (010)
  • shift bit to 4 ,from left to right, but in this case from right to left. 11000001 -> 10100001

so it's overwrite that 3 bits to new 3 bits.



Solution 1:[1]

def overwrite_bit(byte,bits,val,shift):
  if len(byte) > 1:
    raise('not a byte!')
  byte = bytearray(byte)
  byte[0] = byte[0] & ~((2**bits)-1 << shift)
  byte[0] = byte[0] | (val << shift)
  return byte

print(overwrite_bit(b'\xc1',3,2,4)) # 0xa1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1