简体   繁体   English

将两个互斥的字节数组合并为一个

[英]Combine two mutually exclusive byte arrays into one

I have 2 byte arrays of 5 bytes each. 我有2个字节数组,每个数组5个字节。 Each byte array represents 40 flags and I need to combine both arrays into one array of 5 bytes. 每个字节数组代表40个标志,我需要将两个数组组合成一个5字节的数组。 Each of the byte arrays are mutually exclusive which helps, Although I would prefer to validate they are mutually exclusive. 每个字节数组都是互斥的,这很有帮助,尽管我希望验证它们是互斥的。

So my question is, how can I combine the two mutually exclusive byte arrays into one. 所以我的问题是,如何将两个互斥的字节数组合并为一个。

The only way I can think of doing it is bit shifting across both arrays and comparing each value, but there must be an easier way of doing it. 我能想到的唯一方法是在两个数组之间进行位移并比较每个值,但是必须有一种更简单的方法。 Can anyone help? 有人可以帮忙吗?

To combine bits in one byte with bits in another byte, you can use the bitwise-or operator | 要组合一个字节中的位与另一个字节中的位,可以使用按位或运算符| . This operator will set a bit in the resulting byte if that bit was set in first or second byte. 如果该位在第一个或第二个字节中设置,则该运算符将在结果字节中设置一个位。

Example: 例:

byte b1 = 0x12; // 0001 0010
byte b2 = 0x81; // 1000 0001
byte result = (byte)(b1 | b2); // Results in 0x93 = 1001 0011

To combine the two arrays: 合并两个数组:

byte[] flags1 = ...;
byte[] flags2 = ...;
byte[] result = new byte[5];
for(int i = 0; i < 5; i++)
    result[i] = (byte)(flags[i] | flags[2]);

Using the bitwise-AND operator & you can find out if any bit is set in both bytes. 使用按位与运算符&可以确定两个字节中是否都设置了任何位。 Example: 例:

byte b1 = 0x93; // 1001 0011
byte b2 = 0x1A; // 0001 1010
byte result = (byte)(b1 & b2); // Results in 0x12 = 0001 0010

To check if bits are NOT set in both arrays: 要检查两个数组中是否未设置位:

byte[] flags1 = ...;
byte[] flags2 = ...;
for(int i = 0; i < 5; i++)
    if ((byte)(flags[i] & flags[2]) != 0)
        throw new InvalidOperationException("Flags cannot be set in both arrays.");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM