Java 1: 二进制学习
2019-03-31 本文已影响0人
老柯南



public class EncodeUtils {
/**
* int 4个字节 32bite
* 小端法
*
* @param intPara
* @return
*/
public static byte[] int2Bytes(int intPara) {
byte[] bytes = new byte[4];
bytes[0] = (byte) ((int) (intPara >> 0 * 8) & 0xff);
bytes[1] = (byte) ((int) (intPara >> 1 * 8) & 0xff);
bytes[2] = (byte) ((int) (intPara >> 2 * 8) & 0xff);
bytes[3] = (byte) ((int) (intPara >> 3 * 8) & 0xff);
return bytes;
}
public static int bytes2Int(byte[] intbytes) {
if (intbytes == null || intbytes.length != 4) {
throw new IllegalArgumentException("参数错误");
}
int int0 = (intbytes[0] & 0xff) << 0 * 8;
int int1 = (intbytes[1] & 0xff) << 1 * 8;
int int2 = (intbytes[2] & 0xff) << 2 * 8;
int int3 = (intbytes[3] & 0xff) << 3 * 8;
return int0 + int1 + int2 + int3;
}
}
