gpt4 book ai didi

java - 需要帮助理解 int 数组到字节数组的方法和 Little/Big Endian 疑惑?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:19:27 25 4
gpt4 key购买 nike

有几个问题,首先是这个方法,它将 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 View 。使用 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]

关于java - 需要帮助理解 int 数组到字节数组的方法和 Little/Big Endian 疑惑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14574933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com