8

I am working on a project in which I am receiving image data as an array of bytes (1-byte per pixel). Each byte represents a greyscale integer (0-255).

In order to perform a number of functions on the data, I need to convert the byte array into an integer array. please help me..

2 Answers2

19

Anything wrong with the simple approach?

public static int[] convertToIntArray(byte[] input)
{
    int[] ret = new int[input.length];
    for (int i = 0; i < input.length; i++)
    {
        ret[i] = input[i] & 0xff; // Range 0 to 255, not -128 to 127
    }
    return ret;
}

EDIT: If you want a range of -128 to 127:

public static int[] convertToIntArray(byte[] input)
{
    int[] ret = new int[input.length];
    for (int i = 0; i < input.length; i++)
    {
        ret[i] = input[i];
    }
    return ret;
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    this head bow is for the speed of you answering the questions, i thought to answer the question, in between seconds i alarmed as you answered – developer May 19 '11 at 11:07
  • for -128 to 127 what to do extra?? –  May 19 '11 at 11:09
  • 1
    Leave the bit masking away which will sign extend the byte. And yes I agree with Damodar.. almost eerie - maybe google finally created an AI that can pass the Turing Test and tries to test it on SO? :p – Voo May 19 '11 at 11:29
  • Thank you, the `& 0xff`saved me here. Exactly what I was looking for – MoxxiManagarm Aug 28 '19 at 11:42
1

It depends on the use of the resulted int array, but normally, converting a byte array or ByteBuffer into an integer array means "wraping" 4 bytes into 1 integer, e.g. for bitmaps, so in that case I would suggest the following conversion:

IntBuffer ib = ByteBuffer.wrap(input).order(ByteOrder.BIG_ENDIAN).asIntBuffer();
int[] ret = new int[ib.capacity()];
ib.get(ret);
return ret;
Apostolos
  • 3,115
  • 25
  • 28