python bmp - ghdrako/doc_snipets GitHub Wiki

image_file = open(path, "rb")
# Blindly skip the BMP header.
image_file.seek(54)
while True:
  r_string = image_file.read(1)
  g_string = image_file.read(1)
  b_string = image_file.read(1)
  if len(r_string) == 0:
    # This is expected to happen when we've read everything.
    break
   if len(g_string) == 0:
    break
   if len(b_string) == 0:
    break

image_file.close()
def set_bit(v, index, x):
  """Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value."""
  mask = 1 << index   # Compute mask, an integer with just bit 'index' set.
  v &= ~mask          # Clear the bit indicated by the mask (if x is False)
  if x:
    v |= mask         # If x was True, set the bit indicated by the mask.
  return v            # Return the result, we're done.

>>> set_bit(7, 3, 1)
15
>>> set_bit(set_bit(7, 1, 0), 3, 1)
13
def swap_bits(val, i, j):
    """
    Given an integer val, swap bits in positions i and j if they differ
    by flipping their values, i.e, select the bits to flip with a mask.
    Since v ^ 1 = 0 when v = 1 and 1 when v = 0, perform the flip using an XOR.
    """
    if not (val >> i) & 1 == (val >> j) & 1:
        mask = (1 << i) | (1 << j)
        val ^= mask
    return val

>>> swap_bits(7, 3, 1)
13
# testBit() returns a nonzero result, 2**offset, if the bit at 'offset' is one.
def testBit(int_type, offset):
  mask = 1 << offset
  return(int_type & mask)
We first create a mask that has set bit only 
at given position using bit wise shift.
      mask = 1 << position

Then to change value of bit to b, we first
make it 0 using below operation
      value & ~mask

After changing it 0, we change it to b by
doing or of above expression with following
(b << p) & mask, i.e., we return
      ((n & ~mask) | (b << p))
def modifyBit( n,  p,  b):
    mask = 1 << p
    return (n & ~mask) | ((b << p) & mask)

A bytearray in python is an array of bytes that can hold data in a machine readable format