需要帮助理解 int 数组到字节数组的方法和小/大端想知道



有几个问题,首先是这个方法,它将int[]转换为byte[]

public static byte[] intToByte(int[] input){
    ByteBuffer byteBuffer = ByteBuffer.allocate(input.length * 4);
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    intBuffer.put(input);
    byte[] array = byteBuffer.array();
    return array;
}
我正在

制作一个游戏,我必须通过套接字发送一个字节数组,我喜欢这种方法,因为它基本上有效,但我不喜欢使用任何我不真正了解它的作用的东西,所以你能给我一些关于这种方法在做什么的见解吗?我相信它首先为位创造了足够的空间,但为什么它会"乘以"四倍到长度?intBuffer 是否连接到 byteBuffer?因为如果没有,为什么你需要所有 Intbuffer 的东西。

好的最后一个问题,BIG_ENDIANLITTLE_ENDIAN ?例如,在我的其他方法中,将字节数组转换为 int 数组,包含 .order(BIG_ENDIAN) 有什么好处?

public static int[] byteToInt(byte[] input){
   IntBuffer intBuf = ByteBuffer.wrap(input).order(ByteOrder.BIG_ENDIAN).asIntBuffer();
   int[] array = new int[intBuf.remaining()];
   intBuf.get(array);
   return array;
}

我知道BIG_ENDIANLITTLE_ENDIAN只是规定字节的排序方式,但为什么要定义字节序呢? 为什么不直接拥有这个?

IntBuffer intBuf = ByteBuffer.wrap(input).asIntBuffer();

IntBuffer 是 byteArray 的字节数组的 int 视图。使用 IntBuffer 的目的是它的 put(int[]),它允许一次性输入 int 数组。事实上,你可以没有IntBuffer作为

    ByteBuffer byteBuffer = ByteBuffer.allocate(input.length * 4);
    for(int i : input) {
        byteBuffer.putInt(i);
    }
...

结果是一样的。

这证明了BigEndian(默认)和LittleEndian之间的区别

        int[] input = {1,2,3,4};
        ByteBuffer byteBuffer = ByteBuffer.allocate(input.length * 4);
//      byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
        for(int i : input) {
            byteBuffer.putInt(i);
        }
        byte[] array = byteBuffer.array();
        System.out.println(Arrays.toString(array));

输出

[0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4]

取消注释byteBuffer.order(ByteOrder.LITTLE_ENDIAN);,输出将是

[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]
int占用

四个字节,因此您必须分配一个byte[]的长度是int[]的四倍。 asIntBuffer()返回ByteBuffer的视图作为IntBuffer,因此将int[]放入IntBuffer会将所有int转换为四个字节,并将它们放入ByteBuffer中。

字节序定义了int的四个字节写入ByteBuffer的顺序。

至于你的最后一个问题,IntBuffer不是int[],从ByteBuffer.asIntBuffer()获得的IntBuffer也不支持array()方法。 换句话说,这种IntBuffer没有支持int[],因为实现是基于byte[]的。

相关内容

最新更新