Sending ArrayList<integer>() into byte[] format thru USB in Android

My code uses a Modbus CRC16 protocol, which generates a List<Integer> with the hexadecimal values that must be written on the USB port.

enter image description here

I'm trying to convert this ArrayList containing Integer objects to a byte[] array so I can write it via USB.

I tried to implement using IntBuffer but got no success.

public static void SendKey(List<Integer> lst, int deviceaddr, int Key)
        {
            lst.add(deviceaddr & 0xff);
            lst.add(6);
            lst.add(0);
            lst.add(99);
            lst.add((Key >> 8) & 0xff);
            lst.add(Key & 0xff);
            Add_CRC16(lst);

            int[] data = toIntArray(lst);

            ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);        
            IntBuffer intBuffer = byteBuffer.asIntBuffer();
            byteBuffer.order(ByteOrder.BIG_ENDIAN);
            intBuffer.put(data);

            byte[] array = byteBuffer.array();
            ftDev.write(array, array.length, true);

        }

private static void Add_CRC16(List<Integer> Data) {

        // Método detector de erros Cyclic Redundancy Check

        int SaveLo, SaveHi;
        int CRC16Lo = 0xFF;
        int CRC16Hi = 0xff;
        int CL = 0x1;
        int CH = 0xA0;

        for (int b : Data) {
            CRC16Lo ^= b;

            for (int flag = 0; flag < 8; flag++) {
                SaveHi = CRC16Hi;
                SaveLo = CRC16Lo;

                CRC16Hi = CRC16Hi / 2;
                CRC16Lo = CRC16Lo / 2;

                if ((SaveHi & 0x01) == 0x01)
                    CRC16Lo |= 0x80;

                if ((SaveLo & 0x01) == 0x01) {
                    CRC16Hi ^= CH;
                    CRC16Lo ^= CL;
                }
            }

        }

            Data.add(CRC16Lo & 0xff);
            Data.add(CRC16Hi & 0xff);

    }

Should I use ByteArrayOutputStream and DataOutputStream?

Jon Skeet
people
quotationmark

It's not entirely clear what output you're expecting, but given your example code, I suspect you just want:

byte[] bytes = new byte[list.size()];
for (int i = 0; i < list.size(); i++) {
    bytes[i] = (byte) list.get(i).intValue();
}

people

See more on this question at Stackoverflow