converting bits in to integer

后端 未结 3 631
生来不讨喜
生来不讨喜 2021-01-24 11:31

I receive a datapacket containing a byte array and I have to get some integer values from it. Here is a part of the documentation. Can someone help me please?

This comes

3条回答
  •  独厮守ぢ
    2021-01-24 12:04

    Assuming you have java 7, you should be able to read the year as

        int year = 1990
        + ((b[0] & 0b1000_0000) << 5)
        + ((b[0] & 0b0100_0000) << 4)
        + ((b[0] & 0b0010_0000) << 3)
        + ((b[0] & 0b0001_0000) << 2)
        + ((b[0] & 0b0000_1000) << 1)
        + ((b[0] & 0b0000_0100));
    

    and the month as

        int month = 1 
        + ((b[0] & 0b1000_0010) << 3)
        + ((b[0] & 0b0100_0001) << 2)
        + ((b[1] & 0b1000_0000) << 1)
        + ((b[1] & 0b0100_0000));
    

    I let you do the others ints in the same way.

    I don't have java7 and can't test now, I hope I'm not wrong. It's also possible that the order of the bytes is the reverse one.

提交回复
热议问题