How to convert a Byte Array to an Int Array

后端 未结 7 1076
生来不讨喜
生来不讨喜 2020-11-28 12:44

I am reading a file by using:

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


        
7条回答
  •  无人及你
    2020-11-28 13:16

    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.

提交回复
热议问题