Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java lossy XOR between chars

Tags:

java

types

char

xor

I'm not sure how XORing is supposed to be "properly" done between chars in Java. I've seen others do this, but when I have something as simple as:

char a = 'a';
char b = 'b';
char c = (char) a ^ b;

I get a "possible lossy conversion from int to char" compile error. I'm not sure how ints are being brought into this context.

like image 989
MegaZeroX Avatar asked Jan 27 '23 16:01

MegaZeroX


1 Answers

When you use ^ on a char, the operation is done in the char's int value.

Because of operator precedence, the casting comes before the ^.

This means that it compiles to

((char) a) ^ b

Since the casting comes first, the promotion to an int happens last, and you will be trying to assign an int to a char

You want to use parenthesis:

char c = (char) (a ^ b);
like image 70
GBlodgett Avatar answered Jan 31 '23 20:01

GBlodgett