文字コードのための手習いその1 2010/09/21

Javaです。
現行とか次期とかいう用語がでてくるプロジェクトにはかならずといっていいほどでてきて頭を悩ますのがおそらく文字コードだろうと思われます。

ちょっといろいろ理解不足なので、プログラム書いて納得していこうかと思います。

import java.io.UnsupportedEncodingException;

public class TestJis {

public static void main(String[] args) throws UnsupportedEncodingException {
a();
b();
}

static void a() throws UnsupportedEncodingException {
String s = "日本語";
byte[] sjis = s.getBytes("sjis");
byte[] jis = new String(sjis, "sjis").getBytes("jis");
String s_jis = new String(jis, "jis");
System.out.println(s_jis);
for (byte b : sjis) {
System.out.print(Integer.toHexString((int) b) + " ");
}
System.out.println();
int cnt = 0;
for (byte b : jis) {
System.out.print(Integer.toHexString((int) b) + " ");
cnt++;
}
System.out.println();
System.out.println("==>" + cnt);
}

static void b() throws UnsupportedEncodingException{

// 46 7c 4b 5c 38 6c
byte[] top = {0x1b, 0x24, 0x42};
byte[] bottom = {0x1b, 0x28, 0x42};

byte[] bs = {0x46, 0x7c, 0x4b, 0x5c, 0x38, 0x6c};
byte[] jis = sandwich(top, bs, bottom);
System.out.println(new String(jis, "jis"));
for (byte b : jis) {
System.out.print(Integer.toHexString((int) b) + " ");
}
}

/**
* バイトの配列を結合していきます。
*
* @param top
* @param bs
* @param bottom
* @return
*/
static byte[] sandwich(byte[] top, byte[] bs, byte[] bottom) {
byte[] ret = new byte[top.length + bs.length + bottom.length];
int[] pos = {0, top.length, top.length + bs.length};
System.arraycopy(top, 0, ret, pos[0], top.length);
System.arraycopy(bs, 0, ret, pos[1], bs.length);
System.arraycopy(bottom, 0, ret, pos[2], bottom.length);
return ret;
}

}



実行結果はこんな感じででてきますよ。
日本語
ffffff93 fffffffa ffffff96 7b ffffff8c ffffffea
1b 24 42 46 7c 4b 5c 38 6c 1b 28 42
==>12
日本語
1b 24 42 46 7c 4b 5c 38 6c 1b 28 42

: