byte[]とintの変換

1837 ワード

package Server;

/**
 * 
 * @author ghl
 */
public class ConvertG {


	public static void main(String args[]) {
		System.out.println(ConvertG.bytesToInt(ConvertG.intToByte(9001)));

		byte[] bytes3 = new byte[] { 122, 64, (byte) 168, (byte) 192 };
		System.out.println(ConvertG.bytesToInt(bytes3));// -1062715270
		System.out.println(ConvertG.intToByte(ConvertG.bytesToInt(bytes3)));// [122, 64, -88, -64]
		System.out.println(ConvertG.intToBytes(ConvertG.bytesToInt(bytes3)));// [-64, -88, 64, 122]
	}

	/**
	 * @param nNum
	 * @return
	 */
	public static byte[] intToBytes(int nNum) {
		byte[] bytesRet = new byte[4];
		bytesRet[0] = (byte) ((nNum >> 24) & 0xFF);
		bytesRet[1] = (byte) ((nNum >> 16) & 0xFF);
		bytesRet[2] = (byte) ((nNum >> 8) & 0xFF);
		bytesRet[3] = (byte) (nNum & 0xFF);
		return bytesRet;
	}
	
	/**
	 * add by ghl
	 * 
	 * @param i
	 * @return
	 */
	public static byte[] intToByte(int i) {
		byte[] abyte0 = new byte[4];
		abyte0[0] = (byte) (0xff & i);
		abyte0[1] = (byte) ((0xff00 & i) >> 8);
		abyte0[2] = (byte) ((0xff0000 & i) >> 16);
		abyte0[3] = (byte) ((0xff000000 & i) >> 24);
		return abyte0;
	}

	/**
	 * add by ghl
	 * 
	 * @param bytes
	 * @return
	 */
	public static int bytesToInt(byte[] bytes) {
		int addr = bytes[0] & 0xFF;
		addr |= ((bytes[1] << 8) & 0xFF00);
		addr |= ((bytes[2] << 16) & 0xFF0000);
		addr |= ((bytes[3] << 24) & 0xFF000000);
		return addr;
	}
}