XOR操作员未在C 中正确评估

XOR operator not evaluating correctly in C++

本文关键字:评估 操作员 XOR      更新时间:2023-10-16

我正在从c 中从头开始建造一个bigint课程,但是有些东西使我发疯:我的XOR无法正常工作,我不知道为什么。我希望有人能启发我。以下是一个最小的工作示例:

class BigInt
{
    private:
        bool pos;
        int size;  // Number of binary digits to use
        short compare(BigInt input);
    public:
        BigInt(long long input, int inSize) { pos = true; size = inSize; }
};
short BigInt::compare(BigInt input)
{
    // Partial compare function for minimal working example
    // Return:
    //         1: (*this) > input
    //         0: (*this) == input
    //        -1: (*this) < input
    string a = (*this).toDecimal(), b = input.toDecimal();
    bool c = (*this).size > input.size, d = (*this).pos ^ input.pos;
    bool thispos = (*this).pos, inpos = input.pos;
    bool xorpos = (thispos != inpos);
    bool x = true, y = true;
    bool z = x ^ y;
    if ((*this).size > input.size || (*this).pos != input.pos)
        return 1 - ((*this).pos ? 0 : 2);
    else if ((*this).size < input.size)
        return -1 + ((*this).pos ? 0 : 2);
    return 0;
}

我在第一个if语句上有一个断点。以下是我在手表列表中的内容。

    thispos true    bool
    inpos   true    bool
    xorpos  true    bool
    x   true    bool
    y   true    bool
    z   false   bool

有人知道发生了什么事吗?我宁愿避免掌握我的if声明。我从来没有如此简单的XOR使用问题。

据我所知,

应该没有错,但是这些价值观有些东西不会评估它们的期望。

编辑:将代码更改为最小工作示例。

好吧,即使 ^是位XOR操作员,您的初始化

bool thispos = (*this).pos, inpos = input.pos;

需要将源值转换为bool类型。bool类型的值可以保证在算术上下文中充当01。这意味着

bool xorpos = thispos ^ inpos;
如果thisposinpos最初是true

false初始化xorpos

如果您观察到不同的行为,则可能是编译器中的错误。积分到-bool转换可能会错误地实现或类似的东西。

另一个机会是某人通过执行

之类的事情"重新定义"了bool关键字
#define bool unsigned char

这将在第一对初始化中禁用适当的bool语义,并导致^的位性质影响结果。

为什么不简单地 x != y?这也与您的类型更一致。