gpt4 book ai didi

c++ - 二进制逻辑仿真器逻辑错误

转载 作者:行者123 更新时间:2023-11-28 07:57:34 25 4
gpt4 key购买 nike

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

我正在尝试做的是模拟可以在计算机上用 C++ 代码找到的 boolean 逻辑。现在我正在尝试创建一个 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)));
}

添加函数的代码:

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;
}

最佳答案

从哪里开始?

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

这个

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。

关于c++ - 二进制逻辑仿真器逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12367752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com