How to properly get little-endian integer in java

2019-05-23 07:45发布

I need to get 64-bit little-endian integer as byte-array with upper 32 bits zeroed and lower 32 bits containing some integer number, let say it's 51.

Now I was doing it in this way:

 byte[] header = ByteBuffer
            .allocate(8)
            .order(ByteOrder.LITTLE_ENDIAN)
            .putInt(51)
            .array();

But I'm not sure is it the right way. Am I doing it right?

1条回答
Anthone
2楼-- · 2019-05-23 08:19

What about trying the following:

private static byte[] encodeHeader(long size) {
    if (size < 0 || size >= (1L << Integer.SIZE)) {
        throw new IllegalArgumentException("size negative or larger than 32 bits: " + size);
    }

    byte[] header = ByteBuffer
            .allocate(Long.BYTES)
            .order(ByteOrder.LITTLE_ENDIAN)
            .putInt((int) size)
            .array();
    return header;
}

Personally this I think it's even more clear and you can use the full 32 bits.

I'm disregarding the flags here, you could pass those separately. I've changed the answer in such a way that the position of the buffer is placed at the end of the size.

查看更多
登录 后发表回答