最近工作中用到byte转换int,short,long的实现,记录一下
public class MathUtil {
public static byte[] shortToBytes(short num) {
byte[] b = new byte[2];
b[1] = (byte)(num&0xff);
b[0] = (byte)((num>>8)&0xff);
return b;
}
public static short bytesToShort(byte [] b) {
return (short)(b[1]&0xff|(b[0]&0xff)<<8);
}
public static int bytesToInt(byte[] b) {
return (int)(b[3]&0xff|(b[2]&0xff)<<8|(b[1]&0xff)<<16|(b[0]&0xff)<<24);
}
public static byte[] intToBytes(int num) {
byte[] b = new byte[4];
b[3] = (byte)(num&0xff);
b[2] = (byte)(num>>8&0xff);
b[1] = (byte)(num>>16&0xff);
b[0] = (byte)(num>>24&0xff);
return b;
}
//long类型转成byte数组
public static byte[] longToBytes(long number) {
long temp = number;
byte[] b = new byte[8];
for (int i = 0; i < b.length; i++) {
b[i] = new Long(temp & 0xff).byteValue();// 将最低位保存在最低位
temp = temp >> 8; // 向右移8位
}
return b;
}
//byte数组转成long
public static long bytesToLong(byte[] b) {
long s = 0;
long s0 = b[0] & 0xff;// 最低位
long s1 = b[1] & 0xff;
long s2 = b[2] & 0xff;
long s3 = b[3] & 0xff;
long s4 = b[4] & 0xff;// 最低位
long s5 = b[5] & 0xff;
long s6 = b[6] & 0xff;
long s7 = b[7] & 0xff;
// s0不变
s1 <<= 8;
s2 <<= 16;
s3 <<= 24;
s4 <<= 8 * 4;
s5 <<= 8 * 5;
s6 <<= 8 * 6;
s7 <<= 8 * 7;
s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7;
return s;
}
}