3

When I write the code

    string s="000000";
    string d="111111";
    int x=(int)s[0]&(int)d[0];
    char y= (char)x;
    cout <<y << endl;

It works perfectly well and gives me the answer 0.

However, if I replace "&" by "^" (XOR) in the above code, the output given to me is just blank.

Why does this happen?

Note-

  1. I tried to replace (int)s[0]^(int)d[0] by ((int)s[0]+(int)d[0])%2 but nothing changed in the result.
  2. I tried to introduce another variable to see if that solves the problem. But again nothing changed.

    string s="000000";
    string d="111111";
    int x=(int)s[0]^(int)d[0];
    int z=x;
    char y= (char)z;
    cout <<y << endl;
    
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
user185887
  • 643
  • 6
  • 18
  • put `char y = '0' + z` whicih would make y what you need – Albin Paul Dec 12 '19 at 17:57
  • @Yksisarvinen Please feel free to put your answers in the answer section – Lightness Races in Orbit Dec 12 '19 at 18:11
  • @LightnessRaceswithMonica I voted to close this question, because I don't see why OP is performing random bit operations on chars and expect the results to be printable. The question is missing "expected output" to make it clear what is wrong. I suppose my comment is obsolete now with answers being present. – Yksisarvinen Dec 12 '19 at 19:00
  • @Yksisarvinen Just because you voted to close doesn't mean you should post answers in comments. Actually it suggests you didn't want to answer it _at all_, so... – Lightness Races in Orbit Dec 13 '19 at 11:12

2 Answers2

8

Let's assume that your system uses ASCII character encoding (or extended ASCII or UTF-8).

In ASCII, the character '0' is represented by the value 48 (110000₂), and '1' is represented by 49 (110001₂)

110000₂ AND 110001₂ = 110000₂ which represents '0'.

110000₂ XOR 110001₂ = 000001₂ which is a non-printable character that represents start of a heading.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

Why does this happen?

Because you are performing bitwise operations on the integral values that encode the characters. You need to:

  1. Convert the characters '0' and '1' to the integers 0 and 1.
  2. Perform the bitwise operations on the integers.
  3. Convert the resultant to a character.
char c1 = s[0];
char c2 = d[0];

int i1 = c1 - '0';
int i2 = c2 - '0';

int res_i = i1 ^ i2;

char res_c = res_i + '0';

That will work as long as c1 and c2 are limited to the characters '0' and '1'

R Sahu
  • 204,454
  • 14
  • 159
  • 270