如何从左移二进制和解释十六进制数字节数组?

How to interpret hex number byte array from left shift binary sum?

我的 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)。

要检查某个位是否已设置,您可以对该位执行按位与操作。然后检查结果是否等于 0。如果不是,则该位已设置。

例如

00100110
00000010     // checks the second bit
-------- &
00000010     // result != 0, so the bit was set

A char 是无符号的 16 位,所以你可以用它来存储结果。

0020几乎是对的,但是字节颠倒了(00 20,Bit13应该是20 00)。

byte[] flag = new byte[4];      
flag[0] = 0x30;
flag[1] = 0x30;
flag[2] = 0x32;
flag[3] = 0x30;

// Bytes to char, using the 'oversized' short so the numbers won't be out of range
short b1 = Short.parseShort(new String(new byte[]{flag[0], flag[1]}), 16);
short b2 = Short.parseShort(new String(new byte[]{flag[2], flag[3]}), 16);
char i = (char) (b1 | (b2 << 8));

// Print contents as binary string
System.out.println(String.format("%16s", Integer.toBinaryString(i)).replace(' ', '0'));

// Output: 0010000000000000

// Check if 14'th bit is set (at index 13)
boolean isSet = ((i & (1 << 13)) != 0);

System.out.println(isSet); // true

您可以使用该方法检查每个位。只需将 13 替换为您要检查的索引即可。


我在这里使用 char,因为这样打印效果会好一些。您可以使用 short,但每当您将其转换为 int(这可能会隐式发生)时,如果设置了最高有效位,则该值会被填充 1,因为它是 signed 类型。然而,charunsigned,因此它没有这种行为。