Right shift bytes array

Last Update

Introduction

Treat an array of bytes as a series of bit, with the most significant bit starts from index 0 of the array. How can we shift this bits right by a certained number of bit?

The Code In C

void right_shift_bytes(uint8_t *bytes, size_t length, uint8_t shift_bits)
{
  // shouldn't be larger than uint8_t since it's a byte
	uint8_t carry_over = 0;

  // start from LSB
	for (int i = length - 1; i >= 0; i--)
	{
    // just shift if it's first byte
		if (i == length - 1)
			bytes[i] = bytes[i] >> shift_bits;
		else
		{
      // store the carry over of the next byte, here the trick is
      // (1 << shift_bites) - 1, it will give us a mask of the bits that
      // we want to carry over
			carry_over = bytes[i] & ((1 << shift_bits) - 1);

      // add the carry over to the last byte
			bytes[i + 1] |= carry_over << (8 - shift_bits);

      // finally shift the current byte
			bytes[i] = bytes[i] >> shift_bits;
		}
	}
}