首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

用简略的方法实现int和byte数组的转换

2012-12-28 
用简单的方法实现int和byte数组的转换由于需要实现int和byte数组的相互转换,google了一下,发现网上的实现

用简单的方法实现int和byte数组的转换

由于需要实现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个字节保存intByteBuffer buff = ByteBuffer.allocate(4);buff.putInt(i);return buff.array();}
?

?

?

?

?

热点排行