gpt4 book ai didi

java - 如何将字节数组转换为 Int 数组

转载 作者:太空狗 更新时间:2023-10-29 22:42:53 25 4
gpt4 key购买 nike

我正在使用以下方式读取文件:

int len = (int)(new File(args[0]).length());
FileInputStream fis =
new FileInputStream(args[0]);
byte buf[] = new byte[len];
fis.read(buf);

我发现 here .是否可以将 byte array buf 转换为 Int Array ?将 Byte Array 转换为 Int Array 会占用更多空间吗?

编辑:我的文件包含数百万个整数,例如

100000000 200000000 .....(使用普通 int 文件写入)。我把它读到字节缓冲区。现在我想把它包装成 IntBuffer 数组。怎么做 ?我不想将每个字节转换为 int。

最佳答案

您在评论中说过,您希望输入数组中的四个字节对应于输出数组中的一个整数,这样效果很好。

取决于您希望字节是大端还是小端顺序,但是...

 IntBuffer intBuf =
ByteBuffer.wrap(byteArray)
.order(ByteOrder.BIG_ENDIAN)
.asIntBuffer();
int[] array = new int[intBuf.remaining()];
intBuf.get(array);

完成,三行。

关于java - 如何将字节数组转换为 Int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11437203/

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