为什么 xor-ing 两个 char 数组显示垃圾位?

Why is xor-ing two `char` arrays showing garbage bits?

我有两个字符数组A和B,我想对这两个数组进行按位异或。但是输出显示垃圾值。我哪里错了?

我尝试对 char 中的输出进行类型转换,因为 array Aarray B 包含 ASCII 中的 0 and 1。但它没有用。

#include<iostream>
#include<cstdlib>

using namespace std;

int main(){
    char A[4] = {0,1,1,0}; 
    char B[4] = {1,1,1,0};
    char XOR[4];
    cout<< " PRINTING "<<endl;
    for(int i =0; i<4; i++)
    {
        XOR[i] = (char)(A[i]^B[i]);
        cout<<(char)XOR[i];
    }
    cout<<endl;

}

预期输出是 1000,但我得到的输出是垃圾。

char 的流式处理运算符将数据视为 个字符 ,而不是数字。如果要将它们打印为数字,则必须将它们转换为数字才能打印:

cout<< static_cast<int>(XOR[i]);

一种解决方案是使用整数数组使其按您希望的方式工作。 char 是 "letters" 的类型,不是数字的类型。

这是一种可能的解决方案:

#include<iostream>
#include<cstdlib>

using namespace std;

int main(){
    int A[4] = {0,1,1,0}; 
    int B[4] = {1,1,1,0};
    int XOR[4];

    cout << " PRINTING "<< endl;

    for(int i=0; i<4; i++)
    {
        XOR[i] = A[i]^B[i];
        cout<<XOR[i];
    }
    cout<<endl;

}