文字化け覚悟 2010/11/11

Javaです。文字化け覚悟です。
文字化けというより表示されないかもですかね。

プログラマのための文字コード技術入門 (WEB+DB PRESS plus) (WEB+DB PRESS plusシリーズ)
矢野 啓介
477414164X


上記の本のp237にサロゲートと結合文字がのっています。

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 {
{

// これは結合文字です。
print(0x304B309A, "utf16");
// サロゲート文字です。
print(0xD867DE15, "utf16");
}

}

}


結果
実行はmac osx上のeclipseです。
コンソールにでたものをキャプチャしました。



: