How to properly get little-endian integer in java

自闭症网瘾萝莉.ら 提交于 2019-12-07 19:39:49

问题


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:


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.



来源:https://stackoverflow.com/questions/35560836/how-to-properly-get-little-endian-integer-in-java

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