ASCII文字のひみつ

ASCII文字では、大文字と小文字の差のビットはひとつしかない。実際に調べてみると0x20になるから、二進数では0010 0000になることがわかる。よって、文字操作では大文字か小文字かを判定するのにはこういう方法もある。まあ、C言語には標準関数islower()というのがあって、こっちを使う方がいいんですけどね。

なんで最後に &0xff をつけているのかというと、C言語では char + char = int だからです。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
	int i;
	char c;
	
	puts("large character");
	for (c = 'A'; c <='Z'; c++) {
		printf("%c: %2x\n", c, c);
	}
	
	puts("small character");
	for (c = 'a'; c <='z'; c++) {
		printf("%c: %2x\n", c, c);
	}
	
	puts("EOR between large and small character");
	for (i = 0; i < 26; i++) {
		printf("%c ^ %c = %2x\n", 'A'+i, 'a'+i, (('A'+i) ^ ('a'+i)) & 0xff);
	}
	exit(EXIT_SUCCESS);
}