如何将字节数组转换为整数数组 [英] How to convert a Byte Array to an Int Array

查看:40
本文介绍了如何将字节数组转换为整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am reading a file by using:

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

正如我在此处找到的.是否可以将 byte array buf 转换为 Int Array ?将 Byte Array 转换为 Int Array 会占用更多空间吗?

As I found here. Is it possible to convert byte array buf to an Int Array ? Is converting the Byte Array to Int Array will take significantly more space ?

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

my file contains millions of ints like,

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

100000000 200000000 ..... (written using normal int file wirte). I read it to byte buffer. Now I want to wrap it into IntBuffer array. How to do that ? I dont want to convert each byte to int.

推荐答案

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

You've said in the comments that you want four bytes from the input array to correspond to one integer on the output array, so that works out nicely.

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

Depends on whether you expect the bytes to be in big-endian or little-endian order, but...

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

完成,分三行.

这篇关于如何将字节数组转换为整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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