#include <stdio.h>
#include <stdint.h>
void printBinary(uint32_t x);
uint32_t clear_bits(uint32_t reg, uint8_t pos, uint8_t len) {
// Your code here
//1. Create a mask of 1's of len
//1.1 Put a 1 in the len position (e.g 4)
//mask = 1<< len (0001 0000)
//1.2 Subtract 1 to get mask of 1s of length
//mask = ((1<<len)-1) (0000 1111)
//1.3 Move mask to correct position pos
//mask = ((1<<len)-1) << pos
uint32_t mask = ((1<<len)-1) << pos;
//1.4 Apply method to clear reg bits at mask position (invert bits of mask 0000 and and)
//reg &= ~((1<<len)-1) << pos
/*PRINT TESTS
printf("Mask\n");
printBinary(mask);
printf("Reg\n");
printBinary(reg);
printf("~Mask\n");
printBinary(~mask);
printf("reg & ~Mask\n");
printBinary(reg & ~mask);
*/
reg &= ~mask;
return reg;
}
int main() {
uint32_t reg;
uint8_t pos, len;
scanf("%u %hhu %hhu", ®, &pos, &len);
printf("%u", clear_bits(reg, pos, len));
return 0;
}
//FUNCTION TO PRINT BINARY 8 bit
void printBinary(uint32_t x){
//1. Find size of passed int
int num_bits = sizeof(x)*8;
//2. loop through every bit and perform checkbit
//printf("Int value is: %hhu, Num of bits is: %d\n",x, num_bits);
for(int i=num_bits-1;i>=0;i--){
//Prints a space every 4 bits
if ((i+1)%4==0 && i+1 != sizeof(x)*8){
printf(" ");
}
if (x & (1 << i)){
printf("1");
}
else{
printf("0");
}
}
printf("\n");
}Input
255 4 4
Expected Output
15