あるプログラマの日記

プログラマのメモ、出来事、考えたこと、勉強とかの雑記

JISコードのエンコーディングについて

JISでエンコードした文字列のbyte配列のコードには、エスケープシーケンス(ESC (0x1B) とそれに続く一つ以上のバイト)が、2バイトコードの開始と終了位置につきます。
たとえば、"あいうえお"の先頭位置には、ESC $ B (SHIFT IN) が付き終了位置には ESC ( B (SHIFT OUT)がつきます。
次のサンプルコードの出力結果

// test JISコード

public class TestJIS{
  public static void main(String[] argv){
    String testStr = new String("あいうえお");
    byte[] testByte1 = null;
    byte[] testByte2 = null;

    try{
      testByte1 = testStr.getBytes("JIS");	// ISO-2202-JP
      testByte2 = testStr.getBytes("EUC_JP");
    }catch(Exception ex){
    }
    for(int i=0; i<testByte1.length; i++){
      System.out.print(Integer.toHexString(testByte1[i] & 0x00FF).toUpperCase() + " ");
    }

    System.out.println("");
    System.out.println( "[JIS bytes    :" + testByte1.length +"]" );
    System.out.println("");

    for(int i=0; i<testByte2.length; i++){
      System.out.print(Integer.toHexString(testByte2[i] & 0x00FF).toUpperCase() + " ");
    }

    System.out.println("");
    System.out.println( "[EUC_JP bytes :" + testByte2.length + "]");
    System.out.println("");

  }
}

JISの文字列のbyte配列のサイズは16バイトになります。EUC_JPだとbyte配列のサイズは10バイトになります。JISのほうは、エスケープシーケンスがつく分、サイズが大きくなります。

ESC $ B -> [1B 24 42]
ESC ( B -> [1B 28 42]


$ java TestJIS
1B 24 42 24 22 24 24 24 26 24 28 24 2A 1B 28 42
[JIS bytes :16]

A4 A2 A4 A4 A4 A6 A4 A8 A4 AA
[EUC_JP bytes :10]