java - 在 Android 中通过 USB 将 ArrayList<integer>() 发送为 byte[] 格式

标签 java android arrays usb

我的代码使用 Modbus CRC16 协议(protocol),该协议(protocol)生成 List<Integer>必须写入 USB 端口的十六进制值。

enter image description here

我正在尝试将包含 Integer 对象的 ArrayList 转换为 byte[] 数组,以便我可以通过 USB 写入它。

我尝试使用 IntBuffer 来实现但没有成功。

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);

    }

我应该使用 ByteArrayOutputStreamDataOutputStream

最佳答案

尚不完全清楚您期望的输出,但鉴于您的示例代码,我怀疑您只是想要:

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

关于java - 在 Android 中通过 USB 将 ArrayList<integer>() 发送为 byte[] 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28702645/

相关文章:

android - 随机 System.ArgumentException : 'jobject' must not be IntPtr. 零

php将json数组合并为一个数组

c++ - 使用动态内存分配将元素添加到数组中

java - 函数式编程: Self-referencing list in Java (Fibonacci)

java - 删除广告时调整布局大小

android - phonegap 3.0 想要 android 17,但我想要 android 18

javascript - 循环对象数组,并根据某些条件生成新数组

java - 如何在 Sublime Text 3 中使用 JUnit

java - 如何在 netbeans 中使用 hibernate 将图像保存到 mysql 数据库以及如何检索和显示图像

java - 如何在adf中的iterator.excuteQuery()之后再次选择currentRow?