How to convert byte array to integer array

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

To perform a number of functions for the data, I need to convert the byte array to an integer array. please help me..

+6
source share
2 answers

Is there something 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 from -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; } 
+15
source

It depends on the use of the resulting int array, but usually converting a byte array or ByteBuffer into an integer array means “shaking” 4 bytes per 1 integer, for example. for bitmaps, so in this 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; 
+1
source

Source: https://habr.com/ru/post/888523/


All Articles