Bitwise operator understanding

Hello everyone,

In this C++ book I'm looking at, I'm currently at the section that deals with bitwise operators. The book has me a little confused with the following example. I would really appreciate it if someone please explained to me what's going on in the code? I will also paste the books' explanation as well after the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Chapter 9; More Data Types and Operaters
// bitwise operators & (AND)

#include <iostream>
using namespace std;

int main()
{
	char ch;

	do{
	cout << "Enter a character(letter). Type q to exit:";
	cin >> ch;

	// this statement turns off the 6th bit
	if(ch != 'q')
	{
		ch = ch &  223; // ch is now uppercase
		cout << ch << '\n';
	}

	}while(ch!='q');

	return 0;
}


I know what's going on with everything else in the code, like the do-while loop etc, but the bitwise part, I can't quite grasp in this example. However I do know that in a AND bitwise scenario: A bit that is 0 in either operand will cause the corresponding bit in the outcome to be set to 0. So for ie:

1 & 0 = 0
1 & 1 = 1

For XOR:

1^0 = 1

In the above code, this is the books' explanation:

The following program reads characters from the keyboard, and turns any lowercase
letter into uppercase by resetting the sixth bit to 0. As the ASCII character set is
defined, the lowercase letters are the same as the uppercase ones, except that they are
greater in value by exactly 32. Therefore, to uppercase a lowercase letter, you need to
turn off the sixth bit, as this program illustrates:

<code above, in the book however the code is between these paragraphs>


The value 223 used in the AND statement is the decimal representation of 1101 1111.
Hence, the AND operation leaves all bits in ch unchanged, except for the sixth one,
which is set to zero.

Thanks to everyone and anyone's help/input. :)
To understand ch & 223, first convert 223 into 8-bit (since char is 8 bits long) binary. The bitwise AND operater & does boolean multiplications bit by bit across all the 8 bits of the variable ch and the constant 223. The resulting 8-bit character is the uppercase version of the original ch, according to the program.
Last edited on
Topic archived. No new replies allowed.