这需要做很多工作:
public static int byteArrayToLeInt(byte[] b) {
final ByteBuffer bb = ByteBuffer.wrap(b);
bb.order(ByteOrder.LITTLE_ENDIAN);
return bb.getInt();
}
public static byte[] leIntToByteArray(int i) {
final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putInt(i);
return bb.array();
}
此方法使用Java ByteBuffer和程序包中的ByteOrder功能java.nio。在需要可读性的地方,此代码应该是首选。它也应该很容易记住。
我在这里显示了Little Endian字节顺序。要创建Big Endian版本,您只需忽略对的调用order(ByteOrder)。
在性能优先于可读性的代码中(大约快10倍):
public static int byteArrayToLeInt(byte[] encodedValue) {
int value = (encodedValue[3] << (Byte.SIZE * 3));
value |= (encodedValue[2] & 0xFF) << (Byte.SIZE * 2);
value |= (encodedValue[1] & 0xFF) << (Byte.SIZE * 1);
value |= (encodedValue[0] & 0xFF);
return value;
}
public static byte[] leIntToByteArray(int value) {
byte[] encodedValue = new byte[Integer.SIZE / Byte.SIZE];
encodedValue[3] = (byte) (value >> Byte.SIZE * 3);
encodedValue[2] = (byte) (value >> Byte.SIZE * 2);
encodedValue[1] = (byte) (value >> Byte.SIZE);
encodedValue[0] = (byte) value;
return encodedValue;
}
只需反转字节数组索引以从零计数到三即可创建此代码的Big Endian版本。
笔记:
在Java 8中,您还可以使用Integer.BYTES常量,该常量比更为简洁Integer.SIZE / Byte.SIZE。