我有 2 种方法,其中一种将整数转换为字节数组,另一种将字节数组转换为整数。但是当我定义字节数组的长度小于 4 时,它们都出现异常。我该如何解决我的两种方法。
public class Test {
public Test() {
}
public static int getIntegerFromByte(byte[] byteArr) {
return (byteArr[0] ) << 24 | (byteArr[1] & 0xFF) << 16 | (byteArr[2] & 0xFF) << 8 | (byteArr[3] & 0xFF);
}
public byte[] getByteArrayFromInteger(int intValue ,int byteArrSize) {
ByteBuffer wrapped = ByteBuffer.allocate(byteArrSize);
wrapped.putInt(intValue);
byte[] byteArray = wrapped.array();
return byteArray;
}
public static void main (String []args) throws IOException {
Test app = new Test();
byte [] b = app.getByteArrayFromInteger(1, 3);
System.out.println("Length of Byte:\t"+ b.length+ "\n Value: \t"+ getIntegerFromByte(b));
byte [] byteArr = new byte[3];
byteArr[0] = 0;
byteArr[1] = 0;
byteArr[2] = 1;
System.out.println("Length of Byte:\t"+ byteArr.length+ "\n Value: \t"+ getIntegerFromByte(byteArr));
}
}
谢谢