How to convert a Byte Array to an Int Array

后端 未结 7 1077
生来不讨喜
生来不讨喜 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:20

    Solution for converting an array of bytes into an array of integers, where each set of 4 bytes represents an integer. The byte input is byte[] srcByte. The int output is dstInt[].

    Little-endian source bytes:

        int shiftBits;
        int byteNum = 0;
        int[] dstInt = new int[srcByte.length/4]; //you might have to hard code the array length
    
        //Convert array of source bytes (srcByte) into array of integers (dstInt)
        for (int intNum = 0; intNum < srcByte.length/4; ++intNum) {  //for the four integers
            dstInt[intNum] = 0;                                      //Start with the integer = 0
    
            for(shiftBits = 0; shiftBits < 32; shiftBits += 8) {     //Add in each data byte, lowest first
                dstInt[intNum] |= (srcByte[byteNum++] & 0xFF) << shiftBits;
            }
        }
    

    For Big-Endian substitute this line:

        for(shiftBits = 24; shiftBits >= 0; shiftBits -= 8)  //Add in each data byte, highest first
    

提交回复
热议问题