1.long转byte[]
public static byte[] longToBytes(long data) {
byte[] res = new byte[8];
for(int i = 0; i < res.length; i++) {
res[i] = (byte)(data >> 8*i);
}
return res;
}
2.byte[]转long
public static long bytesToLong(byte[] args) {
if(args == null || args.length != 8)
throw(new NullPointerException("非法集合或集合为空!"));
long res = 0;
for(int i = args.length - 1; i >= 0 ; i--) {
res = (res << 8) | (args[i] & 0xff);
}
return res;
}
3.int转byte[]
public static byte[] integerToBytes(int data) {
byte[] res = new byte[4];
for(int i = 0; i < res.length; i++) {
res[i] = (byte)(data >> 8*i);
}
return res;
}
4.byte[]转int
public static int bytesToInteger(byte[] args) {
if(args == null || args.length != 4)
throw(new NullPointerException("非法集合或集合为空!"));
int res = 0;
for(int i = args.length - 1; i >= 0 ; i--) {
res = (res << 8) | (args[i] & 0xff);
}
return res;
}