converting to uppercase

Jun 25, 2011 at 12:00pm
i got a code from google to convert a string to uppercase but i am not able to figure out how is it working...plz help me out....the code is as follows
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<string.h>
#include<conio.h>
using namespace std;
int main()
{
    string mystring;
    getline(cin,mystring);
    
for ( int a = 0; a < strlen ( mystring.c_str() ); a++ )
if ( mystring [ a ] >= 'a' && mystring [ a ] <= 'z' )
{mystring [ a ] &= 0xdf;
cout<<mystring[a];}
else 
cout<<mystring[a];

cin.sync();
cin.ignore();
}

plz tell me what does that bolded line mean and how is it working..
rest all is clear...
thanks a lot
Jun 25, 2011 at 12:15pm
it performs a logical and operation... it is equivalent to mystring[a]=mystring[a]& 0xdf. the and opeartion converts the lower case chars to uppercase
Jun 25, 2011 at 12:23pm
yeah i understood that thing...but didnt understand how is it converting..means what is the use of 0xdf??
Jun 25, 2011 at 12:35pm
0xDF is 11011111 in binary, so that's a byte with all but the 6th bit set.
So when and'ing this with a value where the 6th bit is set, it's equivalent to subtracting 32.
Now when you check an ASCII table ( http://www.asciitable.com/ ), you'll see that the uppercase and lowercase letters are exactly 32 apart.

Replace the line with mystring[a]-='a'-'A'; so it becomes more obvious.
Jun 25, 2011 at 12:36pm
suppose you have 'a' as your character then the char code is 97, converting it to hexadecimal gives 61 which is in hex. now when you logically and 61 and df i.e.(0110 0001 & 1101 1111) you get (0100 0001) which is 41 in hexadecimal when converted back to decimal(int) it is 65 which is the char code for 'A'
Jun 25, 2011 at 12:45pm
thanks a lot....got it
Jun 25, 2011 at 12:55pm
It'd be a lot clearer if you just used toupper
Topic archived. No new replies allowed.