// Reverses a subarray of bits. staticvoidbitarray_reverse(bitarray_t *const bitarray, constsize_t bit_offset, constsize_t bit_length) { size_t left = bit_offset; size_t right = bit_offset + bit_length - 1;
while (left < right) { // Swap the bits at positions left and right. bool left_bit = bitarray_get(bitarray, left); bool right_bit = bitarray_get(bitarray, right);
// Convert a rotate left or right to a left rotate only, and eliminate // multiple full rotations. constsize_t bit_left_amount = modulo(-bit_right_amount, bit_length);
// If the rotation amount is zero, no need to rotate. if (bit_left_amount == 0) { return; }
// Perform the rotation using the reverse method: (a^R b^R)^R = ba constsize_t split_point = bit_offset + bit_left_amount;
// Reverse the first part (a^R). bitarray_reverse(bitarray, bit_offset, bit_left_amount);
// Reverse the second part (b^R). bitarray_reverse(bitarray, split_point, bit_length - bit_left_amount);