How to convert int[] to byte[]

前端 未结 6 525
花落未央
花落未央 2020-11-27 04:39

I have an array of integers which represent a RGB image and would like to convert it to a byte array and save it to a file.

What\'s the best way to convert an array

6条回答
  •  失恋的感觉
    2020-11-27 05:01

    I would use 'DataOutputStream' with '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));
        }
    }
    

    Prints:

    [-1000000, 24000, -1, 40]
    [-1, -16, -67, -64, 0, 0, 93, -64, -1, -1, -1, -1, 0, 0, 0, 40]
    [-1000000, 24000, -1, 40]
    

提交回复
热议问题