我们在处理数据的时候,经常要用到转成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;
}
这篇文章介绍了在处理数据时,如何将short、int和long类型的数据转换成对应的byte数组,主要利用位移操作来实现每个数值的二进制表示。提供的三个方法分别用于转化short、int和long到byte数组。
4601

被折叠的 条评论
为什么被折叠?



