#include <stdio.h>
/*
I added a new function printBinary that takes an unsigned int as an argument.
The printBinary function uses a loop to iterate over the 8 bits of the unsigned int (from most significant bit to least significant bit).
Inside the loop, I use the bitwise right shift operator >> to shift the bits of num to the right by i positions. This effectively divides num by 2^i.
I then use the bitwise AND operator & to mask the result with 1, which gives me the value of the i-th bit (0 or 1).
I print the result using printf with the %d format specifier.
In the main function, I call printBinary after each bitwise OR operation to print the resulting binary pattern.
Now, the output shows the binary pattern as a string of 0s and 1s, which is more readable than the hexadecimal representation.
*/
void printBinary(unsigned int num) {
for (int i = 7; i >= 0; i--) {
printf("%d", (num >> i) & 1);
}
printf("\n");
}
/*
I added a new function countSetBits that takes an unsigned int as an argument.
The countSetBits function uses a loop to iterate over the bits of num.
Inside the loop, I use the bitwise AND operator & to check if the least significant bit (LSB) of num is set (i.e., num & 1 is 1). If it is, I increment the count variable.
I then use the bitwise right shift operator >>= to shift the bits of num to the right by 1 position, effectively dividing num by 2.
The loop continues until num becomes 0.
The function returns the final value of count, which represents the number of set bits in the binary pattern.
In the main function, I call countSetBits after each bitwise OR operation to print the count of set bits.
Now, the output shows the count of set bits in the binary pattern, which is useful for various applications, such as compression, encoding, and cryptography.
*/
int countSetBits(unsigned int num) {
int count = 0;
while (num) {
count += num & 1;
num >>= 1;
}
return count;
}
int main() {
unsigned int num = 0; // Initialize a binary number to 0
// Set the 3rd bit (0b00001000) using a bitwise OR operation
num |= (1 << 3);
printf("After setting 3rd bit: ");
printBinary(num);
printf("Set bits: %d\n", countSetBits(num));
// Set the 6th bit (0b01000000) using a bitwise OR operation
num |= (1 << 6);
printf("After setting 6th bit: ");
printBinary(num);
printf("Set bits: %d\n", countSetBits(num));
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: