Follow me on Twitter for my latest adventures!
I just remembered that I had forgotten the ASCII trick to convert lowercase to uppercase and back. The trick is super simple, you xor the 6th bit (or 5th depending on how you count bits) and that changes the case!
Check this out:
a = 01100001 A = 01000001
See, just the 6th bit changed.
Why is it this way? Simply because the people who invented ASCII thought it was a great idea. If you look at characters a..z, you'll see that all of them have the 6th bit set to 1. The ASCII inventors though, hey, let's set 6th bit to 0 for upper case letters A..Z, then it will be super easy to change case. So they did.
a = 01100001 A = 01000001 b = 01100010 B = 01000010 c = 01100011 C = 01000011 d = 01100100 D = 01000100 e = 01100101 E = 01000101 f = 01100110 F = 01000110 g = 01100111 G = 01000111 h = 01101000 H = 01001000 i = 01101001 I = 01001001 j = 01101010 J = 01001010 k = 01101011 K = 01001011 l = 01101100 L = 01001100 m = 01101101 M = 01001101 n = 01101110 N = 01001110 o = 01101111 O = 01001111 p = 01110000 P = 01010000 q = 01110001 Q = 01010001 r = 01110010 R = 01010010 s = 01110011 S = 01010011 t = 01110100 T = 01010100 u = 01110101 U = 01010101 v = 01110110 V = 01010110 w = 01110111 W = 01010111 x = 01111000 X = 01011000 y = 01111001 Y = 01011001 z = 01111010 Z = 01011010
Also check this out, if you xor a character with a space, you invert the case:
$ perl -le 'print "a"^" "' A $ perl -le 'print "A"^" "' a
Why is that? Because a space ' ' has the value 32, which is 1<<5, which is the 6th bit, which swaps the case!
Bonus
Here are the commands I used for this blog post:
$ perl -e 'printf "%08b\n", ord("K")'
$ perl -e 'printf "%s = %08b %s = %08b\n", $_, ord, uc, ord uc for a..z'
Simple articles best articles.


Facebook
Plurk
more
GitHub
LinkedIn
FriendFeed
Google Plus
Amazon wish list
Comments
UTF-8 is a little more exciting. Yes I know you spec'd ASCII just saying.
I didn't even think about UTF8. Do you've any insight on UTF8 tricks?
Using tricks with Unicode encodings (plural) will end, at some point, in tragedy. You should try to change case with "official" methods.
hat blank swaps case:
perl -e 'print "a" ^ " "'
perl -e 'print "A" ^ " "'
Oh yeah, ' ' is 32, which is 1<<5. Had forgotten this one.
Peteris, liked this one a lot. Thank you.
Yes ASCII (and UTF-8) were designed well.
http://www.pixelbeat.org/docs/utf8_programming.html
Nothing new, we've been doing this for decades. Now get off my lawn, stupid kids... ;-)
This is an awesome trick. Btw, I always forget too the rule for changing the case, but this one for sure I will never forget. Thanks a lot.
Leave a new comment