What the heck does 'A' - 'a' do?Code:char upper(char c){ if( c>='a' && c<='z') return c +='A' - 'a'; else return c; }
This is a discussion on What is this? (stuff in toupper()) within the C Programming forums, part of the General Programming Boards category; Code: char upper(char c){ if( c>='a' && c<='z') return c +='A' - 'a'; else return c; } What the heck ...
What the heck does 'A' - 'a' do?Code:char upper(char c){ if( c>='a' && c<='z') return c +='A' - 'a'; else return c; }
Return the difference in position of 'A' and 'a'. Assuming that the alphabetic char values are in alphabetical order (and that is true for ASCII and its successors), this computes the mapping from each lowercase letter to its uppercase equivalent.
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
In ASCII, the value of a blank is 0x20, or 32 decimal. If you look at an ASCII character chart, you'll see that each upper case and lowercase character are decimal 32 apart.
A capital "A" is decimal 65. A lower case "a" is decimal 97.
65 - 97 = -32.
If c was lower case "a" (97) and you add -32, you get 65 (uppercase "A").
Quite a convoluted way to do it, but it works.
If the input is always a character in the range of a-z, the technique of adjusting by the value of a blank works for ASCII, and EBCDIC as well (although EBCDIC is in the other direction... the lower case sort ascending first).
Todd
Mac and Windows cross platform programmer. Ruby lover.
Quote of the Day
12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.
Amen brother!
Just to clarify: 'a' - 'A' might work for EBCDIC, but checking if the char is between ( 'a' && 'z' ) definitely won't work because the alphabet is fragmented in EBCDIC.
http://www.legacyj.com/cobol/ebcdic.html
I know - that's why I was very careful with my wording.
Thanks.
Mac and Windows cross platform programmer. Ruby lover.
Quote of the Day
12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.
Amen brother!
so if i did c += -32;
should that work as well?
Yes, or you could
c -= 32 ;
or
c -= ' ' ;
Todd
Mac and Windows cross platform programmer. Ruby lover.
Quote of the Day
12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.
Amen brother!
If you wanted to get real obtuse, you could
c &= 0xDF ;
Mac and Windows cross platform programmer. Ruby lover.
Quote of the Day
12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.
Amen brother!
Another alternative; perhaps easier to understand?
But if you want to write portable code, you should use the standard toupper() & tolower() functions instead of trying to write your own.