在c ++中实现"AND"和"OR"时出错

Sha*_*adi 1 c++ mips instructions

参考我之前的问题,我如何在c ++中实现AND和OR操作

我的下一个问题是,有时它输出一些奇怪的数字,例如110010和010101 = 110591.为什么会发生这种情况?

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    long int s;
    long int l;
    long int r;

    cin>>s;
    cout<<endl;
    cin>>l;
    cout<<setfill('0')<<setw (5)<<s<<endl<<setfill('0')<<setw (5)<<l<<endl;
    r=s|l;
    cout<<r<<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Gre*_*ill 6

您似乎在输入数字110010并希望它是二进制的,因为它只有1和0.该数字是十进制数,您需要将其转换为二进制,以便按位操作有意义.

 decimal                    binary
 ---------------------------------
 110010 = 0001 1010 1101 1011 1010
 010101 = 0000 0010 0111 0111 0101
 ---------------------------------
 110591 = 0001 1010 1111 1111 1111 (result of a | b)
Run Code Online (Sandbox Code Playgroud)

以上是您正在使用的数字的二进制表示,分为四位组,因此更容易阅读.