Flip upper case with lower case

If we print the binary() form of ASCII letters:

println(binary('A', 8), hex('A', 2), (byte) 'A'); // 01000001 41 65
println(binary('a', 8), hex('a', 2), (byte) 'a'); // 01100001 61 97

println(binary('Z', 8), hex('Z', 2), (byte) 'Z'); // 01011010 5A 90
println(binary('z', 8), hex('z', 2), (byte) 'z'); // 01111010 7A 122

exit();

We’re gonna notice the only diff. between an uppercase ASCII letter from its corresponding lowercase is that the 3rd bit of the latter is 1.

We can create a CASE_MASK for that 3rd bit like this:
static final byte CASE_MASK = 1 << 5; // 0b00100000

That is, the bit 1 is left-shifted 5 times, which is the same as 0b00100000 in binary, 0x20 in hexadecimal and 32 in decimal.

Now, in order to use that bit-mask as a case bit flipper, we’re gonna need to use the operator ^:

static final byte CASE_MASK = 1 << 5; // 0b00100000

void setup() {
  println(binary(CASE_MASK, 8), hex(CASE_MASK, 2), CASE_MASK); // 00100000 20 32
  println();

  println(binary('A', 8), hex('A', 2), (byte) 'A'); // 01000001 41 65
  println(binary('a', 8), hex('a', 2), (byte) 'a'); // 01100001 61 97

  println(binary('Z', 8), hex('Z', 2), (byte) 'Z'); // 01011010 5A 90
  println(binary('z', 8), hex('z', 2), (byte) 'z'); // 01111010 7A 122
  println();

  println((char) ('A' ^ CASE_MASK)); // 'a'
  println((char) ('a' ^ CASE_MASK)); // 'A'
  println((char) ('Z' ^ CASE_MASK)); // 'z'
  println((char) ('z' ^ CASE_MASK)); // 'Z'

  exit();
}

Now you just need to create a function which flips the case of a whole String. :wink:

P.S.: Alternatively we can use the space ' ' character as the mask, b/c its ASCII value is 32: :flushed:
static final byte CASE_MASK = ' '; // same as 1 << 5

  println((char) ('A' ^ ' ')); // 'a'
  println((char) ('a' ^ ' ')); // 'A'
  println((char) ('Z' ^ ' ')); // 'z'
  println((char) ('z' ^ ' ')); // 'Z'

  exit();
4 Likes