I am comparing the following two characters with &: '\u0874' 'a'
and I get ` as output. I know that 'a' in binary is 01000001 and '\u0874' in binary is(UTF-8 encoding) 11100000:10100001:10110100
How exactly does the & operator work here?
char comp58 = 'a';
char comp96 ='\u0874';
Console.WriteLine(comp96&=comp58);
CodePudding user response:
Firstly, note what what you're actually doing is anding comp96
with comp58
and assigning the result to comp96
by using the &=
operator. Because of this, you are outputting a character rather than an integer.
Secondly, note that the characters in C# are using UTF16.
Thirdly, note that the UTF16 code for a
is actually 00000000 01100001
.
So the AND you're actually performing is:
00000000 01100001 'a'
00001000 01110100 '\u0874'
-----------------
00000000 01100000 Result
And 00000000 01100000
is the UTF16 code for "`" (grave/accent) which is what you're seeing as the output.
Note that if you changed your code to:
Console.WriteLine(comp96 & comp58);
the output would be 96
because now you would be outputting the result of ANDing two chars, which will be an integer.