me gustaría utilizar 'DataOutputStream' con 'ByteArrayOutputStream'.
public final class Converter {
private static final int BYTES_IN_INT = 4;
private Converter() {}
public static byte [] convert(int [] array) {
if (isEmpty(array)) {
return new byte[0];
}
return writeInts(array);
}
public static int [] convert(byte [] array) {
if (isEmpty(array)) {
return new int[0];
}
return readInts(array);
}
private static byte [] writeInts(int [] array) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(array.length * 4);
DataOutputStream dos = new DataOutputStream(bos);
for (int i = 0; i < array.length; i++) {
dos.writeInt(array[i]);
}
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static int [] readInts(byte [] array) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(array);
DataInputStream dataInputStream = new DataInputStream(bis);
int size = array.length/BYTES_IN_INT;
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = dataInputStream.readInt();
}
return res;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public class ConverterTest {
@Test
public void convert() {
final int [] array = {-1000000, 24000, -1, 40};
byte [] bytes = Converter.convert(array);
int [] array2 = Converter.convert(bytes);
assertTrue(ArrayUtils.equals(array, array2));
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(bytes));
System.out.println(Arrays.toString(array2));
}
}
Lienzo:
[-1000000, 24000, -1, 40]
[-1, -16, -67, -64, 0, 0, 93, -64, -1, -1, -1, -1, 0, 0, 0, 40]
[-1000000, 24000, -1, 40]
Tal vez va a obtener respuestas mejores y más puntiagudos si uno habla de razones por las que decide convertir int [] a byte []. –