我们在处理数据的时候,经常要用到转成byte数组的情况,这里记录一下。
public static byte[] short2Bytes(short shortNum) {
byte[] bytes = new byte[2];
bytes[1] = (byte) (shortNum >> 8);
bytes[0] = (byte) shortNum;
return bytes;
}
public static byte[] int2Bytes(int intNum) {
byte[] bytes = new byte[4];
bytes[3] = (byte) (intNum >> 24);
bytes[2] = (byte) (intNum >> 16);
bytes[1] = (byte) (intNum >> 8);
bytes[0] = (byte) intNum;
return bytes;
}
public static byte[] long2Bytes(long longNum) {
byte[] bytes = new byte[8];
bytes[7] = (byte) (longNum >> 56);
bytes[6] = (byte) (longNum >> 48);
bytes[5] = (byte) (longNum >> 40);
bytes[4] = (byte) (longNum >> 32);
bytes[3] = (byte) (longNum >> 24);
bytes[2] = (byte) (longNum >> 16);
bytes[1] = (byte) (longNum >> 8);
bytes[0] = (byte) longNum;
return bytes;
}