Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

a.) Let x be an 8-bit variable (of type char). The following exercises test your

ID: 3628921 • Letter: A

Question

a.) 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.

1) Description: test if bit 0 of x is set

2) Description: while bit 4 of x is clear

3) Description: clear all the odd bits of x while preserving the even bits

4) Description: toggles the even bits of x while keeping the odd bits

5) Description: set bit 4 and clear bit 7 while perserving the other bits

b.)
Using bitwise operators, shift operators, and a single for loop, complete the following C function to count the number of zero-value bits in a variable x of type unsigned short.

unsigned char count_zero(unsigned short x) {
.............................
}

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;
}