2- (Bitwise Operators) (I) Left shifting an unsigned int by 1 bit is equivalent
ID: 3575481 • Letter: 2
Question
2- (Bitwise Operators)
(I) Left shifting an unsigned int by 1 bit is equivalent to multiplying the
value by 2. Write a function power2 that takes two integer arguments number and pow and calculates
number * 2pow
Use the shift operator to calculate the result. Print the values as integers and as bits.
(II) What is the output of this C code?
#include <stdio.h>
1. void main()
2. {
3. int a = 5, b = -7, c = 0, d;
4. d = ++a && ++b || ++c;
5. printf(" %d%d%d%d", a, b, c, d);
6. }
a) 6 -6 0 0
b) 6 -5 0 1
c) -6 -6 0 1
d) 6 -6 0 1
(III) What is the output of this C code?
1. #include <stdio.h>
2. int main()
3. {
4. int x = 2;
5. int y = -4
6. x = x << 1;
7. y = y >> 1;
8. printf("%d %d ", x, y);
9. }
a) 4 -2
b) 1 -8
c) Depends on the compiler
d) Compiler error
Explanation / Answer
-- Code
#include <stdio.h>
void power2(int number, int p)
{
int i;
printf("Given - %d - ",number);
printBinary(number);
// this part shifts the number to left by 1 and it does for p times
for(i=0;i<p;i++)
{
number = number << 1;
}
printf(" After shifting - %d - ",number);
printBinary(number);
}
// this is for printing binary number, used recursion
void printBinary(int n)
{
if(n>0)
{
printBinary(n/2);
printf("%d",n%2);
}
}
int main()
{
power2(10,3); // calls power2 to shift 10 thrice
}
-- Sample Output
Given - 10 - 1010
After shifting - 80 - 1010000
[II]
c) -6 -6 0 1
[III]
d) Compiler error
It shows compiler error because 5th line is not ending with ;
If that is a typo, answer will be a) 4 -2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.