设置数组中字节的 LSB

Set the LSB of bytes in array

我有 2 个字节数组:ary_aary_b,两者大小相同。

我想将 ary_a 中每个字节的 LSB 设置为与 ary_b 中每个字节的 LSB 相同。例如:

数组中的第一个字节:

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

第二个字节:

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

第三名:

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

等等..

试试下面的代码

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'));
}

输出:

10110111
10110111
10110110

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

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);
}

首先从每个字节数组索引中获取最低有效位,然后根据其值零或一设置ary_a[index]。 如果你用 1 做 OR,你会得到最后一位设置 如果你和 ~1,你将得到最后一位未设置。 如果你用 1 做 AND,你将得到最低有效位。 此解决方案适用于 signed int,因此您可以基于相同的逻辑考虑适用于 unsigned int 的解决方案。