2

In this stackoverflow answer there is a piece of code to transform a char to lowercase:

        // tricky way to convert to lowercase
        sb.Append((char)(c | 32));

What is happening in (char)(c | 32) and how is it possible to do the opposite to transform to uppercase?

Community
  • 1
  • 1
Henrik Stenbæk
  • 3,982
  • 5
  • 31
  • 33
  • 2
    Would `ToUpper()` not be sufficient? Or are you looking to be tricksy? – PiousVenom Sep 19 '13 at 21:49
  • @MyCodeSucks `ToUpper()` will end out doing: `if (97 <= (int) c && (int) c <= 122){c &= '\xFFDF';}` (whatever that means) but first after checking for culture and calling `culture.TextInfo.ToUpper()` and I don't need that because I already know that `(c >= 'a' && c <= 'z')` – Henrik Stenbæk Sep 19 '13 at 21:59

1 Answers1

6

This is a cheap ASCII trick, that only works for that particular encoding. It is not recommended. But to answer your question, the reverse operation involves masking instead of combining:

sb.Append((char)(c & ~32));

Here, you take the bitwise inverse of 32 and use bitwise-AND. That will force that single bit off and leave others unchanged.

The reason this works is because the ASCII character set is laid out such that the lower 5 bits are the same for upper- and lowercase characters, and only differ by the 6th bit (32, or 00100000b). When you use bitwise-OR, you add the bit in. When you mask with the inverse, you remove the bit.

paddy
  • 60,864
  • 6
  • 61
  • 103
  • 2
    Agreed. It was pretty common back in the DOS days (maybe not so much on UNIX) when ASCII (and the extended ANSI character set) were gospel, even though people 'knew better'. It was significantly faster on compilers and hardware back then. It may still be faster now, due to lack of branching. However, you can achieve the same without branching by using a lookup table. – paddy Sep 19 '13 at 21:57
  • 3
    Yep, but I reckon Harry Potter would do something as reckless as this, just to get the upper hand on He Who Shall Not Be Named. Bitwisius Operandus!! – paddy Sep 19 '13 at 22:07