java中int、long与byte数组相互转换

来源:互联网 发布:gps数据导入谷歌地球 编辑:程序博客网 时间:2024/05/16 09:46

1、int转换成4个byte数组

public static byte[] intToByteArray2(int a) {          return new byte[] {              (byte) ((a >> 24) & 0xFF),              (byte) ((a >> 16) & 0xFF),                 (byte) ((a >> 8) & 0xFF),                 (byte) (a & 0xFF)          };      }

2、4个byte数组转成int

public static int byteArrayToInt2(byte[] b) {          return   b[3] & 0xFF |                  (b[2] & 0xFF) << 8 |                  (b[1] & 0xFF) << 16 |                  (b[0] & 0xFF) << 24;      } 


3、long转成8个字节数组

public static byte[] longToBytes(long x){    ByteBuffer bb = ByteBuffer.allocate(8);    bb.putLong(0, x);    return bb.array();    }


4、8个字节数组转成long

public static long byteArrayTolong(byte[] b){    ByteBuffer bb = ByteBuffer.allocate(8);    bb.put(b, 0, b.length);    bb.flip();    return bb.getLong();    }



0 0
原创粉丝点击