How to properly get little-endian integer in java

只愿长相守 提交于 2019-12-06 04:24:32

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!