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: 3649134 • 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. The first has been completed for you. (5 pts)

i) Description: if bit 0 of x is set
if (x & 0x01)

ii) Description: while bit 5 and 4 of x is clear


iii) Description: clear the upper 4 bits of x while preserving the lower 4 bits


iv) Description: toggles bits 7, 6, 3, and 2 of x while persevering the rest



v) Description: clear bit 3 and set bit 7 while preserving the other bits


b) Using bitwise operators, shift operators, and a single for loop, complete the following C function to pack the one-value bits in a variable x, of type unsigned short, into bit positions 0 to

Explanation / Answer

please rate- thanks

i) Description: if bit 0 of x is set
if (x & 0x01)

ii) Description: while bit 5 and 4 of x is clear
while(x & 0x30==0)


iii) Description: clear the upper 4 bits of x while preserving the lower 4 bits
x = x & 0xf


iv) Description: toggles bits 7, 6, 3, and 2 of x while persevering the rest

x = x ^ 0xcc

v) Description: clear bit 3 and set bit 7 while preserving the other bits
x=(x | 0x80) & 0xf7


b) Using bitwise operators, shift operators, and a single for loop, complete the following C function to pack the one-value bits in a variable x, of type unsigned short, into bit positions 0 to “number of ones”-1. (5 pts)

#include<stdio.h>
#include<conio.h>
unsigned short pack_ones(unsigned short x) ;
int main()
{unsigned short x = 0x10aa; // has 5 ones
unsigned short y = 0;
y = pack_ones(x);
printf("%X packed is %X ",x,y);
getch();
return 0;
}
unsigned short pack_ones(unsigned short x) {
// count the 1s
unsigned short mask=0x8000,b;
int i,sum=0;
for(i=15;i>=0;i--)
   {b=x&mask;
   if(b!=0)
      sum++;
   mask=mask/2;
    }
b=0;
mask=1;
for(i=0;i<sum;i++)
     {b=b|mask;
      mask=mask<<1;
      }
return b;

}

Example:
unsigned short x = 0b0001000010101010; // has 5 ones
unsigned short y = 0;
y = pack_ones(x);

// After calling pack_ones in this case:
// y = 0b0000000000011111, the 5 ones are packed from bit positing 0 to bit position 4 (i.e. 5 – 1);

unsigned short pack_ones(unsigned short x) {
// Your code here





}