Java xor operation between chars
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22662559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
xor operation between chars
提问by J. Bend
I have the following piece of Java code and while debugging in Eclipse, Windows 7, the variable 'xoredChar' shows no value at all, not null, not '', nothing.
I have the following piece of Java code and while debugging in Eclipse, Windows 7, the variable 'xoredChar' shows no value at all, not null, not '', nothing.
char xoredChar = (char) (stringA.charAt(j)^stringB.charAt(j));
Why is that? I need to understand how can I do this xor operation between two characters in java. What am I missing?
Why is that? I need to understand how can I do this xor operation between two characters in java. What am I missing?
回答by Bathsheba
If stringA
and stringB
are identical, then the XOR operation will yield xoredChar = 0
.
If stringA
and stringB
are identical, then the XOR operation will yield xoredChar = 0
.
A 0 is probably showing in your IDE as nothing since 0 is used as a string terminator in most instances.
A 0 is probably showing in your IDE as nothing since 0 is used as a string terminator in most instances.
回答by Elliott Frisch
Well, if the strings are equal you'll get back a \0
which is not a printable character. Try something like this,
Well, if the strings are equal you'll get back a \0
which is not a printable character. Try something like this,
String stringA = "A";
String stringB = "A";
int j = 0;
char xoredChar = (char) (stringA.charAt(j) ^ stringB.charAt(j));
System.out.printf("'%c' = %d\n", xoredChar, (int) xoredChar);
Output is
Output is
' ' = 0
回答by Harmlezz
As mentioned by the other answers, xoring the same characters results in a \0
value, which has no visual representation. Perhapse you are interested in a small application, which gives you and idea how XOR works on your strings:
As mentioned by the other answers, xoring the same characters results in a \0
value, which has no visual representation. Perhapse you are interested in a small application, which gives you and idea how XOR works on your strings:
public class Example {
public static void main(String[] args) {
String a = "abcde";
String b = a;
for (int idx = 0; idx < b.length(); idx++) {
System.out.printf("xoring <%s> [%s] with <%s> [%s]\n",
a.charAt(0), toBinaryString(a.charAt(0)),
b.charAt(idx), toBinaryString(b.charAt(idx)));
int c = (a.charAt(0) ^ b.charAt(idx));
System.out.printf("result is <%s> [%s]\n",
(char) c, toBinaryString(c));
}
}
}
Have fun!
Have fun!