[java]intをbyteの配列にする 2010/11/11

javaです。

intの値をbyteの配列にします。
あと、byteの配列からintの値にします。


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();
}

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

static void a() {
{
byte[] bs = toBytes(Integer.MAX_VALUE);
printHex(bs);
int i = toInt(bs);
if (i == Integer.MAX_VALUE) {
System.out.println("*** OK");
} else {
System.err.println("*** ouach!!");
}
}

{
byte[] bs = toBytes(Integer.MIN_VALUE);
printHex(bs);
int i = toInt(bs);
if (i == Integer.MIN_VALUE) {
System.out.println("*** OK");
} else {
System.err.println("*** ouach!!");
}
}
}

}


動かした結果
7F FF FF FF
*** OK
80 00 00 00
*** OK

: