1

I have two char arrays A and B. I want to perform bitwise xor on these two arrays. But the output shows a garbage value. Where am I going wrong?

I tried typecasting the output in char since array A and array B contains 0 and 1 in ASCII.But it didn't work.

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

Expected output is 1000, but the output I get is a garbage.

13
  • 1
    Printable ASCII characters start at 32. You are trying to print ASCII characters 0 and 1. To output the values as integers, convert them to e.g. int. Commented May 17, 2019 at 7:56
  • 1
    XOR[i]'s type is already char. Casting it to char isn't doing anything. Commented May 17, 2019 at 7:57
  • I don't think the duplicate mark is appropriate in this case. Commented May 17, 2019 at 8:02
  • @YesThatIsMyName Can you explain why you think so? The solution is the exact same, and the duplicate also tries to print "abnormal" ASCII characters (above 127) and expects to get numerical output instead (in hex for some reason, which admittedly none of the answers look into). The underlying issue is still "char is printed as ASCII char, not integer". If you can find a better duplicate let me know though, I'm sure there are at least 10 more. And with the answers here we got yet another duplicate. Commented May 17, 2019 at 8:13
  • @MaxLanghof Because he uses char doesn't mean it's right using chars ... char is just the wrong type for numbers. In my oppinion he just wasn't aware of this. Thats why my answer tells him to use integer arrays ... and this changes the whole topic and has nothing more to do with printing ASCII characters as integers. Before we really know why he is using char, we can't say its a duplicate. Commented May 17, 2019 at 8:35

2 Answers 2

1

The streaming operators for char treat the data as characters, not as numbers. If you want to print them as numbers, you have to cast them to a number for printing:

cout<< static_cast<int>(XOR[i]); 
Sign up to request clarification or add additional context in comments.

Comments

0

One solution is to use integer arrays to make it work as you wish. A char is a type for "letters", not for numbers.

Here is one possible solution:

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

Comments