【问题标题】:adding 1 to a binary number using logical operations使用逻辑运算将 1 加到二进制数上
【发布时间】:2015-03-24 20:10:05
【问题描述】:

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

问候

【问题讨论】:

    标签: binary logical-operators


    【解决方案1】:

    想一想当您以手写方式执行十进制数的加法时您在做什么。完全一样。


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

    标记从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(从 150)。
    4. 没有必要有 四个 进位位,但为了与手动加法范例保持一致,我还是引入了它们。
    5. 四位是Nibble

    示例 C# 类:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 2011-02-26
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多