C++ Program: Computer Architecture: Bitwise operators. [16] Learn about the cost
ID: 3777942 • Letter: C
Question
C++ Program:
Computer Architecture: Bitwise operators. [16] Learn about the cost-efficient bitwise operators &, |, ~, <<, and >>. Then using only these operators, write in a file bitwise.c the functions: int pow2(int n): returns 2^n. int mul2(int n): returns n/2. int div2(int n): returns 2*n. bool odd(int n): returns 1 if odd, 0 otherwise. Also demonstrate them in your main function.
4. Computer Architecture: Bitwise operators [16] Learn about the efficient bitwise operators & I, r in a file se.c the functions: o int pow2 int n) returns 2 nn. o int mul2(int n) returns n/2 o int div2(int n returns 2*n o bool odd(int n) urns 1 if odd, 0 otherwise Also demonstrate them in your main function and Then using only these operators, writeExplanation / Answer
#include <iostream>
using namespace std;
// method to find the power of 2 using left shift operator
int pow2(int n){
int x=1;
x=x<<(n);
return x;
}
// method to find the n/2 using right shift operator by 1
int mul2(int n){
return n >> 1;
}
// method to find the n*2 using left shift operator by 1
int div2(int n){
return n << 1;
}
//method to find whether a number is odd or even using & operator
bool odd(int n){
if (n & 1) {
return true;
}else{
return false;
}
}
int main()
{
printf("pow: %d ",pow2(4));
printf("mul2: %d ",mul2(8));
printf("div2: %d ",div2(8));
printf("odd: %d ",odd(5));
return 0;
}
input
pow2(4)
mul2(8)
div2(8)
odd(4)
---output-------
pow: 16
mul2: 4
div2: 16
odd: 0
---output-------
input
pow2(4)
mul2(8)
div2(8)
odd(5)
---output-------
pow: 16
mul2: 4
div2: 16
odd: 0
---output-------
Explanation of the bit wise operator
<<====== binary left shift operator
shifting all the bits to left towards MSB by two
>>====== binary right shift operator
shifting all the bits to right by two
&======The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
Note: feel free to ask question/queries. God bless you!!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.