#include <stdio.h> #include <stdint.h> uint8_t setBits(uint8_t reg, int start, int end) { // Make sure positions are valid if (start < 0) start = 0; if (end > 7) end = 7; // Create mask uint8_t mask = ((1 << (end - start + 1)) - 1) << start; // Set the bits return reg | mask; } int main() { uint8_t reg; int start, end; // printf("Enter register value (0-255): "); scanf("%hhu", ®); // Read 8-bit unsigned value // printf("Enter start position (0-7): "); scanf("%d", &start); // printf("Enter end position (0-7): "); scanf("%d", &end); uint8_t result = setBits(reg, start, end); printf("%u\n", result); return 0; }
Test Cases
Test Results
Input
0 1 3
Expected Output
14