I am trying to implement two bitwise functions in C:
set(unsigned *x, unsigned n, unsigned v)
--> Sets the nth bit of the value x to the value v. V is either 0 or 1, and N is [0, 31] for simplicities sake.
flip(unsigned *x, unsigned n)
--> Flips the Nth bit in x. Assume N is [0,31] for simplicities sake.
My implementation:
void set(unsigned *x, unsigned n, unsigned v) {
*x = (1 << n) | v;
}
void flip(unsigned *x, unsigned n) {
*x = n ^ (1 << *x);
}
My problem: The functions don't work logically.
The output from test cases:
Testing set_bit()
set_bit(0x0000004e,2,0) returned 0x00000004 but we expected 0x0000004a set_bit(0x0000006d,0,0) returned 0x00000001 but we expected 0x0000006c set_bit(0x0000004e,2,1) returned 0x00000005 but we expected 0x0000004e set_bit(0x0000006d,0,1) returned 0x00000001 but we expected 0x0000006d set_bit(0x0000004e,9,0) returned 0x00000200 but we expected 0x0000004e set_bit(0x0000006d,4,0) returned 0x00000010 but we expected 0x0000006d set_bit(0x0000004e,9,1) returned 0x00000201 but we expected 0x0000024e set_bit(0x0000006d,7,1) returned 0x00000081 but we expected 0x000000ed
Testing flip_bit()
flip_bit(0x0000004e,0) returned 0x00004000, but we expected 0x0000004f flip_bit(0x0000004e,1) returned 0x00004001, but we expected 0x0000004c flip_bit(0x0000004e,2) returned 0x00004002, but we expected 0x0000004a flip_bit(0x0000004e,5) returned 0x00004005, but we expected 0x0000006e flip_bit(0x0000004e,9) returned 0x00004009, but we expected 0x0000024e