How to convert a Byte Array to an Int Array
Asked Answered
G

7

22

I am reading a file by using:

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

As I found here. Is it possible to convert byte array buf to an Int Array ? Is converting the Byte Array to Int Array will take significantly more space ?

Edit: my file contains millions of ints like,

100000000 200000000 ..... (written using normal int file wirte). I read it to byte buffer. Now I want to wrap it into IntBuffer array. How to do that ? I dont want to convert each byte to int.

Gnaw answered 11/7, 2012 at 16:30 Comment(10)
Why do you want to convert a byte array to an int array?Alasdair
@vidit, Thus I can read integers like int c = array[0]Gnaw
Just loop and copy the value to a new int array?Deucalion
but you could read it like this: int c = (int)array[0];Helminth
@nhahtdh, It will take lots time. I just found it is possible to wrap it in IntBufer. I want to know how ?Gnaw
Whats the format of the file? Does it have only numbers?Alasdair
"will take significantly more space" each int is stored on 32 bits, byte is stored on 8 bits so it will take around 4x more spaceEarthstar
We might be able to help you more, if you add the format of file in your question.Alasdair
@Pshemo, 32 bits ints are stored on that as 4 byte array.Gnaw
@Gnaw Do you want to convert your array to store each 4 bytes in one int element? In that case this may interest you.Earthstar
L
59

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.

Lated answered 11/7, 2012 at 17:24 Comment(4)
This of course assumes that you want each set of 4 bytes to be translated to an int, and not each byte.Zerelda
Yep, the OP implied that in comments to other answers.Lated
How to make the above interpret each byte as one int? An array of 4 bytes becomes an array of four intsCalabro
@typelogic: You can't do it that way. Do it with a manual for loop. int[] intArray = new int[byteArray.length]; for (int i = 0; i < byteArray.length; i++) { intArray[i] = byteArray[i]; }Lated
C
6

Converting every 4 bytes of a byte array into an integer array:

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;
}
Coryza answered 11/7, 2012 at 16:36 Comment(5)
I want 4 byte to convert in int. Not single byte to int. The file is int file.Gnaw
@alessandro: Are you saying you want every 4 bytes of the array to represent an integer?Coryza
what is the use of & with 0xFFMatrona
use of & with 0xFF (decimal : 255 and binary: 11111111) is little endian approach of creating int array from byte array.Retrace
@Matrona the point of the bitwise And operator & is to prevent what you could call "arithmetic casting". Normally when casting (int) someByte it maintains the sign, so negative numbers stay the same. This means that if there is a 1 at the foremost spot of the byte, it will be repeated all the way to the front of the integer. The bitwise & prevents this. I have a small java codesnippet on Pastebin to show the functionality. If you want more information look up "two's complement"Crowded
H
2

In java:

  • byte = 8 bits
  • integer = 32 bits

and for conversion you could do something like:

byte[] byteArray = new byte[] {123, 12, 87};
int[] intArray = new int[byteArray.length];

// converting byteArray to intArray
for (int i = 0; i < byteArray.length; intArray[i] = byteArray[i++]);

System.out.println(Arrays.toString(intArray));

this would output:

[123, 12, 87]
Helminth answered 11/7, 2012 at 16:44 Comment(0)
H
1

Is this ok for you?

    int IntToByte(byte arrayDst[], int arrayOrg[], int maxOrg){
        int i;
        int idxDst;
        int maxDst;
        //
        maxDst = maxOrg*4;
        //
        if (arrayDst==null)
            return 0;
        if (arrayOrg==null)
            return 0;
        if (arrayDst.length < maxDst)
            return 0;
        if (arrayOrg.length < maxOrg)
            return 0;
        //
        idxDst = 0;
        for (i=0; i<maxOrg; i++){
            // Copia o int, byte a byte.
            arrayDst[idxDst] = (byte)(arrayOrg[i]);
            idxDst++;
            arrayDst[idxDst] = (byte)(arrayOrg[i] >> 8);
            idxDst++;
            arrayDst[idxDst] = (byte)(arrayOrg[i] >> 16);
            idxDst++;
            arrayDst[idxDst] = (byte)(arrayOrg[i] >> 24);
            idxDst++;
        }
        //
        return idxDst;
    }

    int ByteToInt(int arrayDst[], byte arrayOrg[], int maxOrg){
        int i;
        int v;
        int idxOrg;
        int maxDst;
        //
        maxDst = maxOrg/4;
        //
        if (arrayDst==null)
            return 0;
        if (arrayOrg==null)
            return 0;
        if (arrayDst.length < maxDst)
            return 0;
        if (arrayOrg.length < maxOrg)
            return 0;
        //
        idxOrg = 0;
        for (i=0; i<maxDst; i++){
            arrayDst[i] = 0;
            //
            v = 0x000000FF & arrayOrg[idxOrg];
            arrayDst[i] = arrayDst[i] | v;
            idxOrg++;
            //
            v = 0x000000FF & arrayOrg[idxOrg];
            arrayDst[i] = arrayDst[i] | (v << 8);
            idxOrg++;
            //
            v = 0x000000FF & arrayOrg[idxOrg];
            arrayDst[i] = arrayDst[i] | (v << 16);
            idxOrg++;
            //
            v = 0x000000FF & arrayOrg[idxOrg];
            arrayDst[i] = arrayDst[i] | (v << 24);
            idxOrg++;
        }
        //
        return maxDst;
    }
Houdini answered 8/10, 2013 at 15:36 Comment(0)
I
0

define "significantly". in java, an int is 4 bytes, so by definition the array would be 4x the space. See: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

And during the conversion, you have to have both, so during the copy portion, you'd be using even more, if you were copying the whole array at once.

as for the conversion, there are many related questions:

Java - converting byte array of audio into integer array

Incredulous answered 11/7, 2012 at 16:35 Comment(0)
M
0

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
Morman answered 2/8, 2018 at 16:14 Comment(0)
I
-1

Create a new int array and copy over the values, casting as needed.

int[] arr = new int[len];

for(int i = 0; i < len; i++)
    arr[i] = (int)buf[i];
Inkberry answered 11/7, 2012 at 16:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.