序例化和反序例化

序例化:

 int index = 0;
            int totalPower = power.getTotalPower(); // 总电量
            int surplusPower = power.getSurplusPower(); // 剩余电量
            byte[] tArr = Conv.int2bytes(totalPower);
            byte[] sArr = Conv.int2bytes(surplusPower);
            powerArray = new byte[11];
            powerArray[index] = 0x3D; // ID
            index += 1;

            byte[] lArr = Conv.short2bytes(8);
            //只是system提供的静态的数组复制方法
            System.arraycopy(lArr, 0, powerArray, index, 2); // 长度
            index += 2;

            System.arraycopy(tArr, 0, powerArray, index, 4); // 总电量
            index += 4;

            System.arraycopy(sArr, 0, powerArray, index, 4); // 剩余电量

序例化的工具类:
public static byte[] int2bytes(int iVal) {
		byte arr[] = new byte[4];
		arr[0] = (byte) ((iVal & 0xff000000) >> 24);
		arr[1] = (byte) ((iVal & 0x00ff0000) >> 16);
		arr[2] = (byte) ((iVal & 0x0000ff00) >> 8);
		arr[3] = (byte) ((iVal & 0x000000ff) >> 0);
		return arr;
	}
	
	public static byte[] mid2bytes(int iVal) {
		byte arr[] = new byte[3];
		arr[0] = (byte) ((iVal & 0x00ff0000) >> 16);
		arr[1] = (byte) ((iVal & 0x0000ff00) >> 8);
		arr[2] = (byte) ((iVal & 0x000000ff) >> 0);
		return arr;
	}

	public static byte[] short2bytes(int iVal) {
		byte arr[] = new byte[2];
		arr[0] = (byte) ((iVal & 0x0000ff00) >> 8);
		arr[1] = (byte) ((iVal & 0x000000ff) >> 0);
		return arr;
	}

反序例化:

这是long的反序例化
 // 终端发送时间(8字节)
        if (offset + 8 <= dataLen) {
            long devMil = Conv.getLongNetOrder(array, offset);
            if (devMil != -1) {
                pos.setDevTime(new Date(devMil));
            }
        }
        offset += 8;

        // 平台接收时间(8字节)
        if (offset + 8 <= dataLen) {
            long recvMil = Conv.getLongNetOrder(array, offset);
            if (recvMil != -1) {
                pos.setRecvTime(new Date(recvMil));
            }
        }
        offset += 8;

反序例化的工具类:
public static long getLongNetOrder(byte[] data, int offset) {
		long l = 0L;
		for (int i = 0; i < 8; i++) {
			l |= Byte.toUnsignedLong(data[offset + i]) << (8 * (7 - i));
		}
		return l;
	}
l |的意思eg:
i=1
i |= 3
12进制数表示为0001,32进制数表示为0011
两个二进制数按位相或,得0011
则i=3
发布了33 篇原创文章 · 获赞 0 · 访问量 1426

猜你喜欢

转载自blog.csdn.net/m0_46086429/article/details/104987099