Fast reading of little endian integers from file

后端 未结 4 1157
无人及你
无人及你 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:33

    Why not read into a 4-byte buffer and then rearrange the bytes manually? It will look like this:

    for (int i=0; i < SIZE_Y; i++) {
        for (int j=0; j < SIZE_X; j++) {
            inp.read(buffer);
            int nextInt = (buffer[0] & 0xFF) | (buffer[1] & 0xFF) << 8 | (buffer[2] & 0xFF) << 16 | (buffer[3] & 0xFF) << 24;
            test_data[j][SIZE_Y - i - 1] = nextInt;
        }
    }
    

    Of course, it is assumed that read reads all four bytes, but you should check for the situation when it's not. This way you won't create any objects during reading (so no strain on the garbage collector), you don't call anything, you just use bitwise operations.

提交回复
热议问题