1. 程式人生 > >Java byte轉int

Java byte轉int

public static int byteToInt(byte b) {  
		return b & 0xFF;  
} 
public static int bytesToInt(byte[] bytes,int offset){
	int i = (int) (((bytes[offset] & 0xFF)<<24)  
			|((bytes[offset+1] & 0xFF)<<16)  
			|((bytes[offset+2] & 0xFF)<<8)  
			|(bytes[offset+3] & 0xFF));  
	return i;
}
public static int bytesToInverseInt(byte[] bytes,int offset){
		int i = (int) ((bytes[offset] & 0xFF)   
			| ((bytes[offset+1] & 0xFF)<<8)   
			| ((bytes[offset+2] & 0xFF)<<16)   
			| ((bytes[offset+3] & 0xFF)<<24));    
	return i;
}
public static long bytesToUInt(byte[] ary, int offset) {
		long value = bytesToInt(ary, offset);
		if (value >= 0)
			return value;
		value = value & 0x7fffffffL;
		value = value + Integer.MAX_VALUE + 1;
		return value;
	}

	public static long bytesToInverseUInt(byte[] ary, int offset) {
		long value = bytesToInverseInt(ary, offset);
		if (value >= 0)
			return value;
		value = value & 0x7fffffffL;
		value = value + Integer.MAX_VALUE + 1;
		return value;
	}


public static int[] bytesToInts(byte[] bytes) {
		if (bytes == null || bytes.length == 0) {
			return null;
		}
		int[] data = new int[bytes.length];
		for (int i = 0; i < bytes.length; i++) {
			data[i] = bytes[i] & 0xFF;
		}
		return data;
	}


public static byte[] reverseByteArray(byte[] bytes) {
		int length = bytes.length;
		byte[] result = new byte[length];
		for (int i = 0; i < length; i++) {
			result[length - 1 - i] = bytes[i];
		}
		return result;
	}