Bitwise AND usage problem understanding

May 15, 2010 at 7:35pm
Im reading a c++ beginners book and there is a chapter about & (bitwise AND). It is using this to convert a lowercase character to its uppercase equivalent. I cant for the life of me figure out why the value 223 is used after the bitwise AND

1
2
3
4
5
6
7
8
9
for(int i=0;i<19;1++)
char ch='a'+i;

cout<<ch<<endl;

//convert to uppercase using bitwise AND
ch=ch & 223;
cout<<"Uppercase :"<<ch<<endl;


The book says that the bitwise AND can be used to turn off the 6th bit in order to make a character its uppercase equivalent. So why not use :
 
ch=ch & 32;


I guess I am lost as to the value that 223 is or something? Can anybody explain it to me?

thanks in advance.
May 15, 2010 at 8:33pm
An upper case letter is 32 decimal (20 hex) less than it's equivalent lower case partner.
So take the lower case a - in decimal 97, in hex 61 in binary 0110 0000
to change to upper case we want to clear only the bit 5 leaving all the other bit's untouched.
When using AND logic, to leave a bit untouched, we AND with 1, to clear it we AND with 0.

so we will need to AND with 1101 1111 which is 223 decimal.
May 15, 2010 at 8:59pm
A better way to write it would be like this:

 
ch &= ~0x20;


The ~ operator makes it easier to see that you're turning a specific bit off.

Hex makes it easier to see which bit you're turning off.

May 15, 2010 at 9:02pm
ch=ch & 32; turns off ALL bits except bit number 6.

ch=ch & ~32; is equivalent to ch=ch & 223; and clears the 6th bit.

ch=ch ^ 32; toggles the 6th bit. You can use it to toggle the case.
May 16, 2010 at 12:09pm
Thanks a million everybody that has cleared it up for me
May 16, 2010 at 4:25pm
You will notice though - that you cannot use AND to set a bit to 1
May 17, 2010 at 10:16am
That's true. To set a bit you'll have to use the bitwise OR operator.
This, for example, turns on the 6th bit: ch=ch | 32;
Topic archived. No new replies allowed.