标题描述;我想仅使用AND OR XOR运算将1加到4位二进制数。我怎样才能做到这一点?
此致
答案 0 :(得分:0)
考虑在长时间添加十进制数时你正在做什么。它完全一样。
在这里,我是如何做到的,显示很多的工作。
将b0
(最低有效位)的四个位标记为b3
(最高有效位),并将{进给位c0
引入c4
。修改后的值为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)
注意:强>
OR
。c3
为0
时,该号码会静默overflowing(从15
转到0
)。示例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();
}
}
}