自定义数据协议,将多位日期保存在字节数组中

自定义数据报协议来保存多位的日期数据。
如2021年5月11日21时58分20秒,使用无符号的String存储为20210511215820,将这个数据保存在6字节的数组中,依次为年月日时分秒。

byte[] time = new byte[6];
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = dateFormat.format(date);
        //截取相应部分转换为int
        int year = Integer.parseInt(format.substring(0,4));
        int month = Integer.parseInt(format.substring(4,6));
        int day = Integer.parseInt(format.substring(6,8));
        int hour = Integer.parseInt(format.substring(8,10));
        int minute = Integer.parseInt(format.substring(10,12));
        int second = Integer.parseInt(format.substring(12,14));
        System.out.println(format);
        //年份最大9999,所以使用14位即可保存,2^14 > 9999,同理月份需要4位,日需要5位
		//位操作,月份左移14位保存在年的高位,日左移18位保存在月份的高位
        month = month << 14;
        day = day << (14 + 4);
		//时分秒原理同上
        minute = minute << (5);
        second = second << (5 + 6);
		//由于一个int为4个字节,所以分为两组,一组保存年月日,另一组时分秒
        int swap1 = year | month | day ;
        int swap2 = hour | minute | second;
        //放入对应数组
        time[0] = (byte) (swap1 & 0xff);
        time[1] = (byte) (swap1 >> 8 & 0xff);
        time[2] = (byte) (swap1 >> 16 & 0xff);
        time[3] = (byte) (swap2 & 0xff);
        time[4] = (byte) (swap2 >> 8 & 0xff);
        time[5] = (byte) (swap2 >> 16 & 0xff);

		//报文解析,前三位为年月日,后面为时分秒
		//将time[0]的8位与time[1]的低6位左移8位共同组成年份的14位数据,月,日解析同理
        int gety = time[0] & 0xff | (time[1] & 0x3f) << 8;
        int getm = (time[1] >> 6) | (time[2] & 0x3) << 2;
        int getd = time[2] >> 2;

        int geth = time[3] & 0x1f;
        int getminute = (time[3] & 0xe0) >> 5 | (time[4] & 0x07) << 3;
        int gets = (time[4] & 0xf8) >> 3 | (time[5] & 0x01) << 5;
        System.out.println(gety + "年" + getm + "月" + getd + "日" + geth + "时" + getminute + '分' + gets + '秒');

输出结果为 2021年5月11日21时58分20秒

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值