java - Android如何构造与此类似的字节数组

标签 java android arrays

我需要一些关于如何在 Java/Android 中做某事的解释。我需要构造一个字节数组/数据包,以便我可以通过 http 请求发送它。我需要它看起来像这样:

- 3 bytes reserved (zero padded)
- 1 byte - Operation Group
- 1 byte - Packet type
- the rest depends on the above

但我不知道如何构造这样的 byte[]

这是我尝试过的:

        String padding = "0000000000"; // first part of packet
        String group = "0xA"; // second part of packet
        String type = "02"; // third part of packet
        String content = "ThisIsATestStringWhichYouWillReadButItsADumbAssStringDudeSorryForYou"; // last part of packet

        String wholePacket = padding.concat(group.concat(type.concat(content)));
        Log.v("","wholePacket : "+wholePacket);

        byte[] bytes = EncodingUtils.getBytes(wholePacket, "UTF-8");

有什么建议吗?

最佳答案

您只需创建一个大小为 sizeof(rest) + 3 + 1 + 1 的 byte[]:

byte[] payload = new byte[] { 0xCA, 0xFE }; // use whatever you need to get your payload into bytes

byte[] buf = new byte[3 + 1 + 1 + payload.length];
// new arrays are automatically initialized with 0, so you don't need to set bytes 0-2 to 0x00
buf[3] = 0x0A; // group
buf[4] = 4; // type

// copy payload into the target
System.arraycopy(payload, 0, buf, 3 + 1 + 1, payload.length);

但是,我建议您使用 Stream 而不是 byte[],因为无论如何您都需要通过 HTTP 连接(已经是流)发送它:

byte[] payload = new byte[] { 0xCA, 0xFE };
OutputStream target = ... // get the output stream of you http connection.
byte group = 0x0a;
byte type = 4;
target.write(new byte[] { 0x00, 0x00, 0x00, group, type }, 0, 5);
target.write(payload);
target.flush();

关于java - Android如何构造与此类似的字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11848011/

相关文章:

javascript - 推送值后未定义的数组

java - 我想使用用户输入的字符串 ex 的前 3 个字母。 "january"结果 :"jan"

java - 双循环链表

java - 在 eclipse 中进行 Android 开发时,我收到 "must override or implement a supertype method"错误,研究的解决方案不起作用

android - 如何加载 libandroid_runtime

java - 如何从Firebase实时数据库获取两个变量

使用 -h 选项时 javac "no source files"

android - 如何将 Google Play Developer API 版本更新到 v3?

javascript - 使用 JavaScript 显示数组元素

java - 随机数组重复