Java 中 byte、byte 数组和 int、long 之间的转换 (三)

2014-11-24 11:41:56 · 作者: · 浏览: 17
;
}

//byte 数组与 int 的相互转换
public static int byteArrayToInt(byte[] b) {
return b[3] & 0xFF |
(b[2] & 0xFF) << 8 |
(b[1] & 0xFF) << 16 |
(b[0] & 0xFF) << 24;
}

public static byte[] intToByteArray(int a) {
return new byte[] {
(byte) ((a >> 24) & 0xFF),
(byte) ((a >> 16) & 0xFF),
(byte) ((a >> 8) & 0xFF),
(byte) (a & 0xFF)
};
}

//byte 数组与 long 的相互转换
public static byte[] longToBytes(long x) {
buffer.putLong(0, x);
return buffer.array();
}

public static long bytesToLong(byte[] bytes) {
buffer.put(bytes, 0, bytes.length);
buffer.flip();//need flip
return buffer.getLong();
}

}


运行测试结果:
byte0=-22
int1=234
bytesInt=[B@de6ced
int3=1417
bytes=[B@c17164
long2=2223