2013年10月30日水曜日

バイト列と文字列の変換

Stringオブジェクトからバイト列に変換するには、getBytesメソッドを利用する
//StringオブジェクトからUTF-8のバイト列に変換
String s = "abc";
byte[] bytes = s.getBytes(”UTF-8”);
for (byte b : bytes){
System.out.println(b);
}

UTF-8のバイト列からStringオブジェクトの生成
//UTF-8のバイト列からStringオブジェクトに変換
byte[] bytes = new byte[]{ (byte)0xe3, (byte)0x81, (byte)0x82, (byte)0xe3, (byte)0x81, (byte)0x84};
try{
String s = new String(bytes, "UTF-8"); //"あい"を出力
System.out.println(s);
}catch (java.io.UnsupportedEncordingException e){}

後者の方はあんまり使わないだろうけど参考までに。
以上です。

0 件のコメント:

コメントを投稿