These are entirely different from the logical operators &&, ||, and !, which operate on whole truth values rather than individual bits— don’t mix them up!
Let’s see the bitwise operators in action. The helper function printBinary() below prints out the binary representation of an unsigned integer, one bit at a time, using the division/remainder approach you may have already seen:
Write a C function that prints the binary representation of an unsigned integer entered by the user. Instead of using division and remainders, you must use bitwise operators (specifically, right-shift and AND) to read and print the bits directly.
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void){
unsigned int num;
printf("Please enter a positive integer: ");
scanf("%d", &num);
printf("Decimal numnber: %d \n", num);
printf("binary number: ");
printBinary(num);
printf("\n");
return 0;
}
//Write your function here
Write a C function that checks whether the \(k\)-th bit of an integer \(n\) is set (1) or not (0). The convention is to count bits from the right, starting at 0. In main(), ask the user to enter an integer as well as the bit position they want to check, call your function to evaluate the bit, and print the conclusion to the screen.
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void){
unsigned int num;
int bit;
printf("Please enter a positive integer and the bit you would like to check: (0 is the right most bit) ");
scanf("%d %d", &num, &bit);
checkBit(num,bit);
//Print out the result here
return 0;
}
//Write your function here
Write a C program to count the number of 1s in the binary representation of a number. Ask the user for an integer, pass it to a function countBits() that counts the set bits and returns this count, and print the result in main().
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void){
unsigned int number;
int numbits;
printf("Please enter a positive integer: " );
scanf("%d", &number);
numbits = countBits(number);
//Print out the result here
return 0;
}
//Write your function here