java中int是32位,long是64位,用byte[]表示分别需要4字节和8字节
public static byte[] intToBytes(int in) {
byte[] result = new byte[4];
for (int i = 3, j = 0; j < 4; i--, j++) {
result[j] = (byte) ((in >>> (i * 8)) & 0xff);
}
return result;
}
public static int bytesToInt(byte[] in) {
int result = 0;
for (int i = 3, j = 0; j < 4; j++, i--) {
result += ((in[j] & 0xff) << (i * 8));
}
return result;
}
public static byte[] longToBytes(long in) {
byte[] result = new byte[8];
for (int i = 7, j = 0; j < 8; i--, j++) {
result[j] = (byte) ((in >>> (i * 8)) & 0xff);
}
return result;
}
public static long bytesToLong(byte[] in) {
long result = 0;
for (int i = 7, j = 0; j < 8; j++, i--) {
result += ((in[j] & 0xff) << (i * 8));
}
return result;
}