Hello I am having some trouble with the bitwise operators and shifts. I believe check_flag() is working however set_flag() is not. Could someone explain what's wrong with it?
#include <stdio.h> void set_flag(int* flag_holder, int flag_position); int check_flag(int flag_holder, int flag_position); int main(int argc, char* argv[]) { int flag_holder = 0; int i; set_flag(&flag_holder, 3); set_flag(&flag_holder, 16); set_flag(&flag_holder, 31); for(i=31; i>=0; i--) { printf("%d", check_flag(flag_holder, i)); if(i%4 == 0) { printf(" "); } } printf("\n"); return 0; } void set_flag(int* flag_holder, int flag_position) { *flag_holder = *flag_holder |= 1 << flag_position; } int check_flag(int flag_holder, int flag_position) { int bit = (flag_holder << flag_position) & 1; if(bit == 0) return 0; else return 1; return bit; }
a |= bis the same as writinga = a | b. Operator & does not copy anything, it only compares each and every bit of two numbers and for returns the result of such comparison. Anyways, I guess what you want is this:*flag_holder |= 1 << flag_position;