メモ帳ブログ @ wiki
[Java] 変換
最終更新:
nina_a
-
view
変換
文字列<-->各種オブジェクトの変換
バイト列
バイト列 -> 文字列
符号化方法を指定する場合
byte[] str_bytes = new byte[]{0x41, 0x42, 0x43}; // ABC
String str = new String(str_bytes, "UTF-8");
文字列 -> バイト列
String str = "ABC";
byte[] str_bytes = str.getBytes();
符号化方法を指定する場合
String str = "ABC";
byte[] str_bytes = str.getBytes("UTF-8");
バイト列 -> 16進数表現文字列
public String bytes2hexString(byte[] array)
{
if(array == null)
throw new IllegalArgumentException(new NullPointerException());
char[] c=new char[array.length*2];
int tmp;
for(int y=0, x=-1; y < array.length; ++y)
{
tmp = (array[y]>>4) & 0x0F;
c[++x]=(char)(tmp>9 ? tmp+'A'-10 : tmp+'0');
tmp = array[y] & 0x0F;
c[++x]=(char)(tmp>9 ? tmp+'A'-10 : tmp+'0');
}
return new String(c);
}
16進数表現文字列 -> バイト列
public byte[] hexString2bytes(String hex)
{
if(hex == null)
throw new IllegalArgumentException(new NullPointerException());
if(hex.startsWith("0x"))
hex = hex.substring(2);
if(hex.length()%2 != 0)
hex = "0" + hex;
hex = hex.toUpperCase();
byte[] b = new byte[hex.length()/2];
char[] c = hex.toCharArray();
for(int x=0, y=-1; x < b.length; ++x)
{
b[x] = (byte)(
((c[++y] > '9' ? c[y] - 'A' + 10 : c[y]-'0') << 4)
+ (c[++y] > '9' ? c[y] - 'A' + 10 : c[y]-'0')
);
}
return b;
}