Henrik Stenbæk
Henrik Stenbæk

Reputation: 4082

tricky way to convert char to lowercase - and how do the opposite

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?

Upvotes: 2

Views: 950

Answers (1)

paddy
paddy

Reputation: 63471

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.

Upvotes: 6

Related Questions