similar question to this are asked many times around Stack over, but I really can't find anywhere that answers this specific case. I have a char, which of course has a binary represenattion. I print it with this method:
void print_binary(unsigned char x) {
int b = 128;
while (b != 0) {
if (b <= x) {
x -= b;
printf("1");
} else
printf("0");
b = b >> 1;
}
}
And I have some char:
char c = 'c';
Now, I need to be able to flip a specific bit in any char/byte.To really spell it out, I need a function with this signature:
char flip_bit(int idx, char c) { So, I give it a char, and a index. It should then flip the bit at the spot of the index, and return a new char.
Solutions that doesnt work for me
In similar looking questions there have been given some solutions that I can't use for this issue spefically:
int mask = 0x90; // 10010000
int num = 0xE3; // 11100011
num ^= mask;
This doesnt work, because I need to do this dynamically, and cannot hardcode every byte for xor'ring with. IF someone could show me how to implement this in the above described function, that would be great.
Or this solution:
char c = 'c';
c |= 1UL << 4;
This works for flipping bit 4 from a 0 to a 1. But I can't get it to work the other way around. Also I need something where it's not necessary for me to specify whehter it should change into a 1 or a 0, but just flip it.
c |= 0UL << 4; # this has no effect
Cant someone help me?
EDIT: This question has been closed, since it sounds a lot like this one, however, if one takes the time to read what what I have written here, you will notice that none of the proposed solutions to that questions satisfies the spefications that I have written