Bitwise Operations are getting me mad.

This is a discussion on Bitwise Operations are getting me mad. within the C Programming forums, part of the General Programming Boards category; Hello,
first say I'm not good with bit operations (I'm still learning and practing with them) so if my question ...

Bitwise Operations are getting me mad.

Hello,
first say I'm not good with bit operations (I'm still learning and practing with them) so if my question is so trivial forgive me.

I'm trying to modify a bit of a character and keep the others intact (the last one), when i try to put a one it seems be working but when i try to put a zero it works sometimes but others don't. The two simple functions I'm using are the following:

For example if I use 't' (int value 116) as argument, put_one returns 'u' (int value 117) what seems to be correct. The problem is with put_zero, it should return the same value ('t' int value 116) but it returns 'D' int value 68.
So, what I'm doing wrong? Is there any better way to do this task?

Assuming put_zero is trying to clear the least significant bit, the constant value you're and-ing with is wrong. The constant you've written is the decimal number 11111110, not the binary value. The decimal value you want to use is 254 = binary 11111110.

In decimal, the low 8 bits of 11111110 = b'11000110. 116 = b'01110100. Anding the two together gives 01000100, which is the 68 you're seeing.

Most people use hex (0xFE) or octal (0376) for this since there's a natural mapping between each digit and a fixed number of bits. For hex, each digit represents 4 bits (1111 = 0xf, 1110 = 0xe). For octal, each digit represents 3 bits (011 = 03, 0111 = 07, 0110 = 6).

But for clearing bits, the typical C idiom is to use something like

x &= ~1; // replace 1 with the value of the bits to clear

The ~ operator flips all of the bits in the constant, so the value you put in indicates the bits you are clearing.