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