Bitwise operations a.) Let x be an 8-bit variable (of type char). The following
ID: 3638504 • Letter: B
Question
Bitwise operationsa.) Let x be an 8-bit variable (of type char). The following exercises test your knowledge of bit masking. For the following, write a single line of C code that represents the given description. The first has been completed for you.
i) Description: test if bit 0 of x is set
if (x & 0x01)
ii) Description: while bit 3 of x is clear
iii) Description: clear all the even bits of x while preserving the odd bits
iv) Description: toggles the odd bits of x while keeping the even bits
v) Description: set bit 2 and clear bit 6 while preserving the other bits
b) Using bitwise operators, shift operators, and a single for loop, complete the following C function to count the number of 1-value bits in a variable x of type unsigned short.
unsigned char count_zero(unsigned short x)
{
//your code
}
Explanation / Answer
please rate - thanks
message me if any problem
i) Description: test if bit 0 of x is set
if (x & 0x01)
ii) Description: while bit 3 of x is clear
while(x & 0x8 == 0)
iii) Description: clear all the even bits of x while preserving the odd bits
x = x & 0xAA
iv) Description: toggles the odd bits of x while keeping the even bits
x = x ^ 0xAA
v) Description: set bit 2 and clear bit 6 while preserving the other bits
x=x& 0xBD + 0x2
b) Using bitwise operators, shift operators, and a single for loop, complete the following C function to count the number of 1-value bits in a variable x of type unsigned short.
unsigned char count_zero(unsigned short x)
{
//your code
unsigned short mask=0x8000,b;
int i,sum=0;
for(i=15;i>=0;i--)
{b=a&mask;
if(b!=0)
sum++;
mask=mask/2;
}
return sum;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.