C言語でchar文字判定
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 5 using namespace std; 6 7 int main(){ 8 9 string sjis = "\x88\xa2\x82\x70\x90\xb3\x93\x60"; 10 cout << sjis << endl; 11 12 for ( int i = 0;i < sjis.length(); i++){ 13 char hex[3]; 14 char testHex[8]; 15 sprintf(testHex, "%x", (char*)sjis.at(i)); 16 hex[0] = testHex[6]; 17 hex[1] = testHex[7]; 18 hex[2] = '\x0'; 19 puts(hex); 20 21 if ( strncmp(hex, "88", 2) == 0 ){ 22 cout << "Match!" << endl; 23 } else { 24 cout << "Not match..." << endl; 25 } 26 } 27 }
実行結果
$ ./sjis 阿Q正伝 88 Match! a2 Not match... 82 Not match... 82 Not match... 90 Not match... b3 Not match... 93 Not match... 93 Not match...
同じようなコードをcharで書くとこんな感じになった。
やっていることとしては「char(1Byte) → char(2Byte…もとのビット列を16進数で表したもの)」
1 #include <stdio.h> 2 #include <string.h> 3 4 int main(){ 5 6 unsigned char sjis[9] = {0x88,0xa2,0x82,0x70,0x90,0xb3,0x93,0x60}; 7 printf("%s\n",sjis); 8 9 char testHex[8]; 10 11 for (int i=0;i < 9;i++) { 12 sprintf(testHex, "%02x", sjis[i]); 13 printf("\n"); 14 for (int j=0;j < 8;j++) { 15 printf("number: %d %c\n",j,testHex[j]); 16 } 17 } 18 }