#include <stdio.h>
#define BITS_IN_BYTE (8)// can be replaced by CHAR_BIT from limits.h
// helper macro to derive max bit position given the datatype
#define MAX_BIT_POS(x) ( (sizeof(x) * BITS_IN_BYTE) - 1 )
// function allowe mods
typedef enum mode_func{
MODE_CLR =0,// clear bit
MODE_SET =1// set bit
} mode_func_t;
// function return status
typedef enum status_mod{
STATUS_NO_ERROR =0,// operation complete
STATUS_INVALID_POS =1,// invalid bit position
STATUS_INVALID_MOD =2// invalid function mode
} status_mod_t;
char *status_msg_arr[] = {
"success",
"invalid position",
"invalid mode" };
// function to modify bit at specified position
status_mod_t modifyBit(unsigned char *reg, int pos, mode_func_t mode) {
// check pos for valid value
if (pos>MAX_BIT_POS(*reg)) {return STATUS_INVALID_POS;}
switch (mode){
case MODE_CLR:
*reg &= ~(1<<pos);
break;
case MODE_SET:
*reg |= (1<<pos);
break;
default:
return STATUS_INVALID_MOD;
}
return STATUS_NO_ERROR;
}
int main() {
unsigned char reg;
int pos;
mode_func_t mode;
scanf("%hhu %d %d", ®, &pos, &mode);
status_mod_t status = modifyBit(®, pos, mode);
if (status == STATUS_NO_ERROR){
printf("%d", reg);
}
else{
printf(" error: %s!",status_msg_arr[status]);
}
return 0;
}
Input
10 3 1
Expected Output
10