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

问题描述

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

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会占用更多空间吗?

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

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

解决方案

您已经在注释中说过,您希望输入数组中的四个字节对应于输出数组中的一个整数,所以效果很好./p>

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

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

完成,分为三行.

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);

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 ?

Edit: my file contains millions of ints like,

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);

Done, in three lines.

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

08-21 00:00