byte数组与int的互转

在Java中,byte数组与整型(int)的互转。

1、byte数组到整型(int)

	/**
	 * byte数组转换为整型
	 * @param b
	 * @return
	 */
	public static int byteArray2Int(byte[] b) {
        int value = 0;
        for (int i = b.length-1; i >=0; i--) {
            int shift = (b.length-1 - i) * 8;
            value += (b[i] & 0x000000FF) << shift;
        }
        
        return value;
	}


2、整型(int)到byte数组

/**
	 * 整型转换为byte数组
	 * @param b
	 * @return
	 */
	public static byte[] int2ByteArray(int b) {
        byte[] value = new byte[4];
        
        for (int i = 4-1; i >=0; i--) {
            int shift = i * 8;
            value[4-1 - i] = (byte)((b & (0x000000FF << shift))>>shift);
        }
        
        return value;
	}	


posted @ 2017-03-20 11:43  hongweigg  阅读(60)  评论(0)    收藏  举报