Fast reading of little endian integers from file

后端 未结 4 1161
无人及你
无人及你 2020-12-15 11:13

I need to read a binary file consisting of 4 byte integers (little endian) into a 2D array for my Android application. My current solution is the following:

         


        
4条回答
  •  既然无缘
    2020-12-15 11:39

    I don't think it is necessary to reinvent the wheel and perform the byte reordering for endianness again. This is error prone and there is a reason a class like ByteBuffer exists.

    Your code can be optimized in the sense that it wastes objects. When a byte[] is wrapped by a ByteBuffer the buffer adds a view, but the original array remains the same. It does not matter wheather the original array is modified/read from directly or the ByteBuffer instance is used.

    Therefore, you only need to initialize one instance of ByteBuffer and also have to set the ByteOrder once.

    To start again, just use rewind() to set the counter again to the beginning of the buffer.

    I have taken your code and modified it as desribed. Be aware that it does not check for errors if there are not enough bytes in the input left. I would suggest to use inp.readFully, as this will throw EOFException if not enough bytes to fill the buffer are found.

    int[][] test_data = new int[SIZE_X][SIZE_Y];
    ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[4]).order(ByteOrder.LITTLE_ENDIAN);
    for (int i=0; i < SIZE_Y; i++) {
        for (int j=0; j < SIZE_X; j++) {
            inp.read(byteBuffer.array());
            byteBuffer.rewind();
            test_data[j][SIZE_Y - i - 1] = byteBuffer.getInt();
        }
    }
    

提交回复
热议问题