Rahul Verma :
I've found this code for swapping case, but I'm a bit confused on how it works.
class Main {
private static String swapCase(String s) {
String r = "";
for (char c : s.toCharArray())
r += c ^= 32; // this line
return r;
}
public static void main(String[] args) {
System.out.println(swapCase("Hello"));
}
}
I understood that it loops over each character. But, I can't wrap my head around the line (especially the XOR operator)
r += c ^= 32;
I mean what's the significance of 32
. How it swaps the case.
Can somebody help me?
Eugene :
This is how ASCII was set-up.
Letter from a-z
have the 6-th bit set to 1
; while letters from A-Z
have the 6-th bit set to 0
.
32 = 100000 // the 6-th bit is set to 1
doing a XOR with an int
will invert that 6-th bit.
You could do a little of debugging and see yourself:
for (char c : s.toCharArray()) {
System.out.println(Integer.toBinaryString((int) c));
c ^= 32; // this line
System.out.println(Integer.toBinaryString((int) c));
}