In: Computer Science
Fill in the code for the following C functions. Function srl performs a logical right shifting using arithmetic right shift (given by value xsra), followed by other operations not including right shifts or division. Function sra performs an arithmetic right shift using a logical right shift (given by value xsrl), followed by other operations not including right shift or division. you may use the computation 8*size of (int) to determine w, the number of bits in data type int. The shift amount k can change from 0 to w-1.
unsigned srl (unsigned x, int k){
unsigned xsra = (int) x>> k;
.
.
.
}
int sra (int x, int k){
int xsrl = (unsigned) x >> k;
.
.
.
}
Solution:
#include <stdio.h>
unsigned srl(unsigned x, int k)
{
/* arithmetic right shifting */
unsigned xsra = (int) x >> k;
int w = sizeof(unsigned) << 3;
unsigned mask = ~(0xff << (w - k));
return xsra & mask;
}
int sra(int x, int k)
{
/* logical right shifting */
int xsrl = (unsigned) x >> k;
int w = sizeof(int) << 3;
unsigned sign = !!((0x1 << (w - 1)) & x);
unsigned mask = (~sign + 1) << (w - k);
return xsrl | mask;
}
//driver funtion to test
int main(int argc, char **argv)
{
printf("%.8x\n", srl(0x1 << 16, 8));
printf("%.8x\n", srl(~0x0, 6));
printf("%.8x\n", srl(0x0, 6));
printf("\n");
printf("%.8x\n", sra(0x9 << 26, 8));
printf("%.8x\n", sra(~0x0, 6));
printf("%.8x\n", sra(0x0, 6));
return 0;
}
Output:
Please give thumbsup, if you like it. Thanks.