Tuesday, December 15, 2009

Fast Case Converter

Often I find myself needing to convert between upper case to lower case and vice versa. This is a fairly simple thing to do if you understand ASCII encoding. A good reference for the ASCII Table can be found here. As you can see, to convert a letter to lower case you would add 32 to the current value and subtract 32 to convert it from lower to upper. However to implement this it takes a few lines of code to put some conditions in that check to see the current case and decide to add or subtract.

I was looking at the ASCII Table the other day and came up with a simplistic method to swap the case of a given character. That is to exclusively-or the value of the character with 0x20. This will convert the upper case to lower and the lower to upper. Its probably the fastest method to swap ,CPUs can xor in one cycle (excluding memory load time). However you still need some type of conditions to make sure the character is actually a letter and not a number of symbol.

Enjoy!