What the heck does 'A' - 'a' do?Code:char upper(char c){ if( c>='a' && c<='z') return c +='A' - 'a'; else return c; }
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.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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
Mainframe assembler programmer by trade. C coder when I can.
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.
Mainframe assembler programmer by trade. C coder when I can.
so if i did c += -32;
should that work as well?
Yes, or you could
c -= 32 ;
or
c -= ' ' ;
Todd
Mainframe assembler programmer by trade. C coder when I can.
If you wanted to get real obtuse, you could
c &= 0xDF ;
Mainframe assembler programmer by trade. C coder when I can.
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.