Keithin8a
Keithin8a

Reputation: 961

Combine two mutually exclusive byte arrays into one

I have 2 byte arrays of 5 bytes each. Each byte array represents 40 flags and I need to combine both arrays into one array of 5 bytes. 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?

Upvotes: 0

Views: 119

Answers (1)

Martin Mulder
Martin Mulder

Reputation: 12934

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

Upvotes: 1

Related Questions