如何在java中正确获取little-endian整数
问题描述:
我需要得到64位小端整数作为字节数组,高32位归零,低32位包含一些整数,假设它是51。
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.
现在我这样做了:
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?
答
如何尝试以下方法:
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;
}
就我个人而言,我认为它更清晰,你可以使用完整的32位。
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.