如果你需要更多的信息,尽管问。
我要做的就是用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;
}发布于 2012-09-11 18:57:30
从哪里开始?
正如注释中所指出的,返回指向静态变量的指针是错误的。
这
out[0] = nor(nor(a, b), carry); 应该是
out[0] = xor(xor(a, b), carry);这个out[1] = or(and(b,carry),and(a,b));也是不正确的。当a == true和carry == true时,out[1]必须为true。
add32假设索引0为最低有效位,int32tobinary和int32tobinary假设索引0为最低有效位。
https://stackoverflow.com/questions/12367752
复制相似问题