近期java项目中需要解析来自c/c++的字节数据,但是解析的过程中涉及到了字节数组数据大端、小端排序的问题,所以整理补充了基本类型short、int、long与byte数组以分别大端和小端相互转换的方法。
/**
* 将int转为高字节在前,低字节在后的byte数组(大端)
* @param n int
* @return byte[]
*/
public static byte[] intToByteBig(int n) {
byte[] b = new byte[4];
b[3] = (byte) (n & 0xff);
b[2] = (byte) (n >> 8 & 0xff);
b[1] = (byte) (n >> 16 & 0xff);
b[0] = (byte) (n >> 24 & 0xff);
return b;
}
/**
* 将int转为低字节在前,高字节在后的byte数组(小端)
* @param n int
* @return byte[]
*/
public static byte[] intToByteLittle(int n) {
byte[] b = new byte[4];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
return b;
}
/**
* byte数组到int的转换(小端)
* @param bytes
* @return
*/
public static int bytes2IntLittle(byte[] bytes )
{
int int1=bytes[0]&0xff;
int int2=(bytes[1]&0xff) 40 & 0xff);
b[1] = (byte) (n >> 48 & 0xff);
b[0] = (byte) (n >> 56 & 0xff);
return b;
}
/**
* long类型转byte[] (小端)
* @param n
* @return
*/
public static byte[] longToBytesLittle(long n) {
byte[] b = new byte[8];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
b[4] = (byte) (n >> 32 & 0xff);
b[5] = (byte) (n >> 40 & 0xff);
b[6] = (byte) (n >> 48 & 0xff);
b[7] = (byte) (n >> 56 & 0xff);
return b;
}
/**
* byte[]转long类型(小端)
* @param array
* @return
*/
public static long bytesToLongLittle( byte[] array )
{
return ((((long) array[ 0] & 0xff) |