- /*将int转为低字节在前,高字节在后的byte数组
- b[0] = 11111111(0xff) & 01100001
- b[1] = 11111111(0xff) & (n >> 8)00000000
- b[2] = 11111111(0xff) & (n >> 8)00000000
- b[3] = 11111111(0xff) & (n >> 8)00000000
- */
- public byte[] IntToByteArray(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;
- }
- //将低字节在前转为int,高字节在后的byte数组(与IntToByteArray1想对应)
- public int ByteArrayToInt(byte[] bArr) {
- if(bArr.length!=4){
- return -1;
- }
- return (int) ((((bArr[3] & 0xff) << 24)
- | ((bArr[2] & 0xff) << 16)
- | ((bArr[1] & 0xff) << 8)
- | ((bArr[0] & 0xff) << 0)));
- }
- public static byte[] double2Bytes(double d) {
- long value = Double.doubleToRawLongBits(d);
- byte[] byteRet = new byte[8];
- for (int i = 0; i < 8; i++) {
- byteRet[i] = (byte) ((value >> 8 * i) & 0xff);
- }
- return byteRet;
- }
- public static double bytes2Double(byte[] arr) {
- long value = 0;
- for (int i = 0; i < 8; i++) {
- value |= ((long) (arr[i] & 0xff)) << (8 * i);
- }
- return Double.longBitsToDouble(value);
- }