文字コードのための手習いその2 2010/11/11

Javaです。文字コードのための手習いその2です。

まずこちらにある対応表をベースに実験です。



package a;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public class A {

/**
* バイトの配列を16進数表現で標準出力します。
*
* @param bs
*/
static void printHex(byte[] bs) {
for (byte b : bs) {
int i = (int) b;
String s = String.format("%h", 0x00000000ff & i).toUpperCase();
System.out.print((s.length() < 2 ? "0" : "") + s + " ");
}
System.out.println();
}

/**
* intをバイト配列にします。
*
* @param a
* @return
*/
static byte[] toBytes(int a) {
byte[] bs = new byte[4];
bs[3] = (byte) (0x000000ff & (a));
bs[2] = (byte) (0x000000ff & (a >> 8));
bs[1] = (byte) (0x000000ff & (a >> 16));
bs[0] = (byte) (0x000000ff & (a >> 24));
return bs;
}

/**
* バイトの配列をintにします。
*
* @param bs
* @return
*/
static int toInt(byte[] bs) {
return ByteBuffer.wrap(bs).asIntBuffer().get();
}

/**
* バイトの配列を結合していきます。
*
* @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;
}

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

static void print(int i, String characterset)
throws UnsupportedEncodingException {
byte[] bs = toBytes(i);
print(bs, characterset);
}

static void print(byte[] bs, String characterset)
throws UnsupportedEncodingException {
String s = new String(bs, characterset);
System.out.println(characterset + ":" + s);
}

static void a() throws UnsupportedEncodingException {
{
System.out.println("♂♀");

// Shift_JIS-2004 (JIS X 0213:2004 Appendix 1) vs Unicode mapping
// tableより
// 0x8189 U+2642 # MALE SIGN
// 0x818A U+2640 # FEMALE SIGN
print(0x8189, "sjis");
print(0x818A, "sjis");

// EUC-JIS-2004 (JIS X 0213:2004 Appendix 3) vs Unicode mapping
// tableより
// 0xA1E9 U+2642 # MALE SIGN
// 0xA1EA U+2640 # FEMALE SIGN
print(0xA1E9, "EUC_JP_LINUX");
print(0xA1EA, "EUC_JP_LINUX");

// ISO-2022-JP-2004 vs Unicode mapping tableより
// 3-2169 U+2642 # MALE SIGN
// 3-216A U+2640 # FEMALE SIGN
print(sandwich(new byte[] { 0x1B, 0x24, 0x42 }, new byte[] { 0x21,
0x69 }, new byte[] { 0x1B, 0x28, 0x42 }), "ISO2022JP");
print(sandwich(new byte[] { 0x1B, 0x24, 0x42 }, new byte[] { 0x21,
0x6A }, new byte[] { 0x1B, 0x28, 0x42 }), "ISO2022JP");

// 最後にunicode
print(0x2642, "utf16");
print(0x2640, "utf16");

// String s = "♂";
// byte[] bs = s.getBytes("ISO2022JP");
// printHex(bs);
// System.out.println(new String(bs, "ISO2022JP"));
}

}

}


結果

♂♀
sjis:♂
sjis:♀
EUC_JP_LINUX:♂
EUC_JP_LINUX:♀
ISO2022JP:♂
ISO2022JP:♀
utf16:♂
utf16:♀

: