converting bits in to integer

后端 未结 3 605
生来不讨喜
生来不讨喜 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 11:44

    First, I'd convert this to an integer:

    import java.nio.ByteBuffer;
    import java.nio.ByteOrder;
    
    int timestamp = ByteBuffer.wrap(byte_array).order(ByteOrder.LITTLE_ENDIAN).getInt();
    

    Next, I'd take it apart:

    int yearCode  = (timestamp >> 26) & 0b111111;
    int monthCode = (timestamp >> 22) & 0b1111;
    int dayCode   = (timestamp >> 17) & 0b11111;
    int hourCode  = (timestamp >> 12) & 0b11111;
    int minCode   = (timestamp >> 6)  & 0b111111;
    int secCode   = (timestamp >> 0)  & 0b111111;
    

    The masking in the first line and shifting in the last line are not strictly necessary, but are left in for clarity.

    The final step is to add 1900 to the yearCode and you're done!

提交回复
热议问题