由于需要实现int和byte数组的相互转换,google了一下,发现网上的实现方法基本都是用位运算操作实现的,比较复杂,这里提供一种简单的方法,用java.nio包中的ByteBuffer实现,代码如下:
/**
* byte数组转int.
*
* @param b
* 要转换的byte数组
* @return 转换结果
*/
public static int byte2int(byte[] b) {
return ByteBuffer.wrap(b).getInt();
}
/**
* int转byte数组
*
* @param i
* 要转换的int值
* @return 转换的结果
*/
public static byte[] int2byte(int i) {
// 用4个字节保存int
ByteBuffer buff = ByteBuffer.allocate(4);
buff.putInt(i);
return buff.array();
}