使用逻辑运算将二进制数加 1

adding 1 to a binary number using logical operations

如标题所述;我想仅使用 AND OR XOR 运算将 1 加到 4 位二进制数。我怎样才能做到这一点?

此致

想一想当您手写加法时您在做什么。一模一样


这是我的做法,展示了很多的工作。

b0(最低有效位)到b3(最高有效位)的四位标记出来,引入5个进位,c0c4。修改后的值为b3', b2', b1', b0',所以你的半字节、进位位和修改后的值为:

{     b3  b2  b1  b0  }
{ c4  c3  c2  c1  c0  }
{     b3' b2' b1' b0' }

它们之间的关系是:

c0  = 1 (this is to flip the least significant bit)

b0' = XOR(b0, 1)
c1  = AND(b0, 1)

b1' = XOR(b1, c0)
c2  = AND(b1, c0)

b2' = XOR(b2, c1)
c3  = AND(b2, c1)

b3' = XOR(b3, c2)
c4  = AND(b3, c2)

注:

  1. 不需要使用OR
  2. 四位的选择是任意的-超过第一位,逻辑是copy/pasta
  3. 当最后一个进位位c30时,数字静默为overflowing(从15变为0)。
  4. 不需要四个进位,但为了与手加范式保持一致,我还是引入了它们。
  5. 四位是一个Nibble

示例 C# class:

public class Nibble
{
    const int bits = 4;

    private bool[] _bools = new bool[bits];

    public void Reset()
    {
        for ( int i = 0; i < _bools.Length; i++ )
            _bools[i] = false;
    }

    public void Increment()
    {
        bool[] result = new bool[bits];
        bool[] carries = new bool[bits + 1];

        carries[0] = true;

        for ( int i = 0; i < bits; i++ )
        {
            result[i] = _bools[i] ^ carries[i];
            carries[i + 1] = _bools[i] && carries[i];
        }

        if ( carries[bits] )
            Console.WriteLine("Overflow!");

        _bools = result;
    }

    public byte Value
    {
        get
        {
            byte result = 0;
            for ( int i = 0; i < bits; i++ )
            {
                if ( _bools[i] )
                    result += (byte)(1 << i);
            }
            return result;
        }
    }
}

用法:

static class Program
{
    static void Main()
    {
        var nibble = new Nibble();
        for ( int i = 0; i < 17; i++ )
        {
            Console.WriteLine(nibble.Value);
            nibble.Increment();
        }
    }
}

Run on Ideone here