-3

I have two questions actually

I am trying to do encryption in C++ using the XOR operation. When i encrypt any two characters i get the ? as the encrypted character why is that?

Here is a sample of my code Xoring a and b.

#include<iostream>
using std::cout;
using std::cin;
int main()
{
    char x='a';
    char y='b';
    char d=x^y;
    cout<<"a xor b = "<<d<<"\n";
    return 0;
}
  • 2
    You might want to read a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Also, `char x = "a";` is invalid so your (first) question is moot. – Rakete1111 Sep 28 '17 at 01:14
  • 3
    It seems you are asking one question (which quote do I use) but really wanting to ask another (why does xor-ing two characters not give the result I want). Consider [edit]ing your question to clarify your actual question – Tas Sep 28 '17 at 01:19
  • What output did you expect for this program? – M.M Sep 28 '17 at 01:36
  • I expect to get different answers when xoring different characters but i get the same answers for almost xoring any two different characters – Yousif Dafalla Sep 28 '17 at 01:37
  • 1
    `'a' == 0x61`, `'b' == 0x62`. Hence `x ^ y` produces 3 which is a [control character](https://en.wikipedia.org/wiki/ASCII#Control_characters) and not printable – phuclv Sep 28 '17 at 01:56

1 Answers1

3

When you output characters which are not printable (and below the 'space' which is 32, most of them are) you are getting question mark or square depending on where you do it. To see the integer value of the XOR, replace d with (int)d

isp-zax
  • 3,833
  • 13
  • 21
  • or simply use [`cout << +d`](https://stackoverflow.com/q/14644716/995714) – phuclv Sep 28 '17 at 01:54
  • Space is not always 32. In addition to being the final frontier, it's actual value depends on the character encoding being used. – user4581301 Sep 28 '17 at 02:30
  • @user4581301, indeed, space depends on locale, however, in the example present no one called std::setlocale(), so default one is classic ASCII with the space 32 and control characters 0-31. – isp-zax Sep 28 '17 at 03:28