如何在java中正确获取little-endian整数 [英] How to properly get little-endian integer in java

查看:224
本文介绍了如何在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.

这篇关于如何在java中正确获取little-endian整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆