【问题标题】:Binary logic emulator logic error二进制逻辑仿真器逻辑错误
【发布时间】:2012-09-11 10:30:54
【问题描述】:

如果您需要更多信息,请询问。

我要做的是模拟可以在 C++ 代码中的计算机上找到的布尔逻辑。现在我正在尝试创建一个 32 位加法器。当我运行测试代码时,我得到了 32 的输出,这是错误的,它应该是 64。我相当确定我的 add 函数是正确的。这些门的代码是:

bool and(bool a, bool b)
{
return nand(nand(a,b),nand(a,b));
}

bool or(bool a, bool b)
{
return nand(nand(a,a),nand(b,b));
}

bool nor(bool a, bool b)
{
return nand(nand(nand(a,a), nand(b,b)),nand(nand(a,a), nand(b,b)));
}

add函数的代码:

bool *add(bool a, bool b, bool carry)
{
static bool out[2];

out[0] = nor(nor(a, b), carry);
out[1] = or(and(b,carry),and(a,b));

return out;
}

bool *add32(bool a[32], bool b[32], bool carry)
{
static bool out[33];
bool *tout;

for(int i = 0; i < 32; i++)
{
    tout = add(a[i], b[i], (i==0)?false:tout[1]);
    out[i] = tout[0];
}
out[32] = tout[1];

return out;
}

我用来测试的代码是:

bool *a = int32tobinary(32);
bool *b = int32tobinary(32);
bool *c = add32(a, b, false);
__int32 i = binarytoint32(c);

这两个函数是:

bool *int32tobinary(__int32 a)
{
static bool _out[32];
bool *out = _out;
int i;

for(i = 31; i >= 0; i--)
{
    out[i] = (a&1) ? true : false;
    a >>= 1;
}

return out;
}

__int32 binarytoint32(bool b[32])
{
int result = 0;
int i;

for(i = 0; i < 32; i++)
{
    if(b[i] == true)
        result += (int)pow(2.0f, 32 - i - 1);
}

return result;
}

【问题讨论】:

  • 你试过什么?诸如逐步/ printf调试之类的东西,看看它在什么时候偏离了您的预期?
  • 听起来像是调试器的工作。无论如何,返回指向静态变量的指针通常是个坏主意。
  • orand 是 C++ 中的保留字,不能用作标识符。一个体面的编译器会抱怨这一点。我推断您可能正在使用 MSVC 或旧的编译器。
  • 我认为 add32 需要从右向左添加,即i 应该从 LS 位开始,这似乎是您代码中的第 31 位?

标签: c++ boolean logic


【解决方案1】:

从哪里开始?

如 cmets 中所述,返回指向静态变量的指针是错误的。

这个

out[0] = nor(nor(a, b), carry); 

应该是

out[0] = xor(xor(a, b), carry);

这个out[1] = or(and(b,carry),and(a,b)); 也不正确。 out[1] 必须是 true,当 a == truecarry == true 时。

add32 假定索引 0 为 LSB,int32tobinaryint32tobinary 假定索引 0 为 MSB。

【讨论】:

  • 我认为,执行位也在错误的结尾?
  • 另外,我将 out[1] = 行更改为:out[1] = or(and(xor(a,b),carry),and(a,b));,根据此处的图表,我认为这是正确的:en.wikipedia.org/wiki/Adder_(electronics)“全加器逻辑图”
猜你喜欢
  • 2012-12-17
  • 2011-10-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多