【发布时间】:2016-09-10 17:08:35
【问题描述】:
我的 android 应用程序正在接收从 C# 应用程序发送的数据字节数组。我需要解释这些字节。
在 C# 应用程序中,表单中有 16 个复选框(Bit0 到 Bit15),代码显示了对这些复选框结果的处理。
ushort flag = (ushort)(
(Bit0.Checked ? (1 << 0) : (0)) +
(Bit1.Checked ? (1 << 1) : (0)) +
(Bit2.Checked ? (1 << 2) : (0)) +
(Bit3.Checked ? (1 << 3) : (0)) +
(Bit4.Checked ? (1 << 4) : (0)) +
(Bit5.Checked ? (1 << 5) : (0)) +
(Bit6.Checked ? (1 << 6) : (0)) +
(Bit7.Checked ? (1 << 7) : (0)) +
(Bit8.Checked ? (1 << 8) : (0)) +
(Bit9.Checked ? (1 << 9) : (0)) +
(Bit10.Checked ? (1 << 10) : (0)) +
(Bit11.Checked ? (1 << 11) : (0)) +
(Bit12.Checked ? (1 << 12) : (0)) +
(Bit13.Checked ? (1 << 13) : (0)) +
(Bit14.Checked ? (1 << 14) : (0)) +
(Bit15.Checked ? (1 << 15) : (0)));
flag 被传递给下面描述的函数,然后被发送到我的 Android 应用程序。
public static void setFlag(List<Byte> data, ushort flag)
{
for (int i = 0; i < 2; i++)
{
int t = flag >> (i * 8);
data.Add((byte)(t & 0x00FF));
}
}
在Android应用程序中,数据以4字节数组的形式接收,然后转换为十进制
public String bytesToAscii(byte[] data) {
String str = new String(data);
return str.trim();
}
// This returns the decimal
Integer.parseInt(bytesToAscii(flag), 16)
例如,当在 C# 应用程序中检查 Bit13 时; Andriod 应用程序接收一个 4 字节的数组,代表十六进制数:
flag[0] = 0x30;
flag[1] = 0x30;
flag[2] = 0x32;
flag[3] = 0x30;
先转换成0020再转换成十进制:
Integer.parseInt(bytesToAscii(flag), 16); // 32
我需要解析 32 来确定 Bit13 被选中。 Bit13 只是 32 的一个例子。我需要弄清楚选择了哪个或多个 Bit(0 到 15)。
【问题讨论】:
-
为什么接收的数据是 4 字节的数组而不是 2 字节的数组?
-
为什么要乘以 8?如果您有两个字节,则 data[0]
-
@JornVernee 他正在添加 2 个字节(0 和 1) - 但我没有得到转换的整个过程......
-
我不知道我收到 4 个字节而不是 2 个字节的原因。我不完全理解 C# 部分,因为它是由其他开发人员开发的。幸运的是,我得到了他们的源代码。根据
setFlag(),它是2字节,但在他们的系统文档中,大小长度是N * 2字节。这就是我收到 4 个字节的原因。