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

ale*_*dro 16 java arrays int byte endianness

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

int len = (int)(new File(args[0]).length());
    FileInputStream fis =
        new FileInputStream(args[0]);
    byte buf[] = new byte[len];
    fis.read(buf);
Run Code Online (Sandbox Code Playgroud)

正如我在这里找到的.有可能转换byte array bufInt Array?转换Byte ArrayInt Array将占用更多的空间?

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

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

Lou*_*man 33

您在评论中已经说过,您希望输入数组中的四个字节对应于输出数组上的一个整数,因此可以很好地解决.

取决于您是否期望字节为big-endian或little-endian顺序,但是......

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

完成,分为三行.

  • 当然,这假定您希望将每4个字节的集合转换为一个int,而不是每个字节。 (2认同)

Chr*_*gis 5

将字节数组的每4个字节转换为整数数组:

public int[] convert(byte buf[]) {
   int intArr[] = new int[buf.length / 4];
   int offset = 0;
   for(int i = 0; i < intArr.length; i++) {
      intArr[i] = (buf[3 + offset] & 0xFF) | ((buf[2 + offset] & 0xFF) << 8) |
                  ((buf[1 + offset] & 0xFF) << 16) | ((buf[0 + offset] & 0xFF) << 24);  
   offset += 4;
   }
   return intArr;
}
Run Code Online (Sandbox Code Playgroud)