Welcome to our comprehensive guide on C Bit Rotation! In this lesson, we'll delve into the fascinating world of bit manipulation, focusing on rotating bits in a number. Let's get started!
Bit rotation is a fundamental operation in computer programming that involves shifting the bits of a number to a different position. This operation can be used for various purposes, such as encryption, multiplication, or generating random numbers.
Before we dive into bit rotation, let's understand how numbers are represented in binary form. For instance, the decimal number 1011 is equivalent to 11 in binary. Each digit (bit) in a binary number has a value, with the least significant bit (LSB) being 0 or 1, and the most significant bit (MSB) being 128, 64, 32, 16, 8, 4, 2, or 1.
Shifting a binary number involves moving all its bits to the left or right. A left shift increases the most significant bit (MSB), while a right shift decreases the least significant bit (LSB).
Bit rotation operations involve moving the bits in a circular fashion. There are two types of bit rotation operations:
Bit Rotate Left (RL): Moves all bits to the left by a certain number of positions. The vacated rightmost positions are filled with zeros.
Bit Rotate Right (RR): Moves all bits to the right by a certain number of positions. The vacated leftmost positions are filled with the rightmost bit (MSB).
In C programming, the built-in functions rotl() and rotr() are used for left and right rotation, respectively. These functions are part of the <bits/byteorder.h> header file.
Let's write a simple C program to perform bit rotation. We'll create two functions for left and right rotation, as shown below:
#include <stdio.h>
#include <bits/byteorder.h>
void rotl(int num, int shift) {
num = _Rotation(num, shift);
printf("Number after Left Rotation (RL) by %d bits: %d\n", shift, num);
}
void rotr(int num, int shift) {
num = _Rotation(num, shift) >> (32 - shift);
printf("Number after Right Rotation (RR) by %d bits: %d\n", shift, num);
}
int _Rotation(int num, int shift) {
return (num << shift) | (num >> (32 - shift));
}
int main() {
int num = 0b01010101; // Hexadecimal: 0x55
int shift = 2;
printf("Number before rotation: %d (0x%X)\n", num, num);
rotl(num, shift);
rotr(num, shift);
return 0;
}In the above code, we define two functions: rotl() and rotr(). The _Rotation() function is a helper function that performs the actual bit rotation.
In the main() function, we define a binary number num and a rotation shift value. We then call the rotl() and rotr() functions, demonstrating the bit rotation operations on the given number.
What does the `rotl()` function do in the given C program?
To practice bit rotation and other bit manipulation techniques, visit the CodeYourCraft C Programming section. Happy coding! ✅