197k views
22 votes
Write a C program that reads a hexadecimal value from the keyboard and then stores the value into an unsigned char variable. Read two int values p and n from the keyboard, where the values are less than 8. Change the initial hexadecimal value in the following way: Shift the n bits starting at position p, so that they form the n least significant bits of the result. The remaining bits of the result are set to 0. Display the result using printf %x.

User Pmdj
by
3.4k points

1 Answer

6 votes

Answer:

#include<stdio.h>

int main(){

unsigned char var;

int p,n;

printf("a: ");

scanf("%x",&var);

printf("p: ");

scanf("%d",&p);

printf("n: ");

scanf("%d",&n);

while(1){

char command;

scanf("%c",&command);

if(command=='S')

var=var else if(command=='R'){

var=var & ~(((1<<n)-1)<<(p-1));

} else if(command=='F'){

var=var ^ (((1<<n)-1)<<(p-1));

} else if(command=='D'){

printf("a = %02x H : ",var);

int i;

for(i=7;i>=4;i--){

printf("%d",((1<<i)&(var))>>i);

printf(" ");

for(i=3;i>=0;i--){

printf("%d",((1<<i)&(var))>>i);

printf(" B\\");

}

}

} else if(command=='I'){

printf("a = ");

scanf("%x",&var);

}

}

}

Step-by-step explanation:

The C source code gets user inputs from a keyboard as integer numbers, p and n, which is converted to binary (8 bits of one and zero value) as the memory for the input hexadecimal number and character values are also inputs from the keyboard, used as flags to determine the way the hexadecimal number is stored or displayed.

User CoronA
by
3.5k points