-1

I have 2 arrays of bytes: ary_a and ary_b, both are same size.

I want to set the LSB of every byte in ary_a same as the LSB of every byte in ary_b. For example:

First byte in the array:

ary_a[0] = 10110110
ary_b[0] = 00101011
//then ary_a[0] will be:
ary_a[0] = 10110111

Second byte:

ary_a[1] = 10110111
ary_b[1] = 00101011
//then ary_a[1] will be:
ary_a[1] = 10110111 //does not change 

Third:

ary_a[2] = 10110111
ary_b[2] = 00101010
//then ary_a[2] will be:
ary_a[2] = 10110110

And so on..

GPraz
  • 298
  • 4
  • 13

2 Answers2

1

Try code below

var ary_a = new byte[]
{
    182, //1011 0110
    183, //1011 0111
    183  //1011 0111
};

var ary_b = new byte[]
{
    43,  //0010 1011
    43,  //0010 1011
    42   //0010 1010
};

for(var i = 0; i<3; i++)
{
    ary_a[i] = (byte)((ary_a[i] & ~1)|(ary_b[i] & 1));

    // print output
    Console.WriteLine(Convert.ToString(ary_a[i], 2).PadLeft(8, '0'));
}

Output:

10110111
10110111
10110110

Fiddle: https://dotnetfiddle.net/0xQ342

Niyoko
  • 7,512
  • 4
  • 32
  • 59
0
for (int index = 0; index < ary_a.Length; index++)
    {
        int aLeast = LeastSigBit(ary_a[index]);
        int bLeast = LeastSigBit(ary_b[index]);

        ary_a[index] = bLeast == 1 ? (byte)(ary_a[index] | 1) : (byte)(~(1) & ary_a[index]);
    }

public static int LeastSigBit(int value)
{
    return (value & 1);
}

First get the least significant bit from each byte array index and then set ary_a[index] based on its value zero or one. If you do OR with 1, you will get the last bit set If you AND with ~1, you will get the last bit unset. If you do AND with 1, you will get the least significant bit. This solution works for signed int, So you can think of solution which works for unsigned int based on the same logic.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197