I am writing some kind of performance-sensitive C # code that deals with character comparisons. I recently discovered a trick where you can determine if char is equal to one or more others without branching if the difference between them is 2.
For example, let's say you want to check if char is U + 0020 (space) or U + 00A0 (non-breaking space). Since the difference between them is 0x80, you can do this:
public static bool Is20OrA0(char c) => (c | 0x80) == 0xA0;
as opposed to this naive implementation, which would add an extra branch if the character was not a space:
public static bool Is20OrA0(char c) => c == 0x20 || c == 0xA0;
How the first works, since the difference between the two characters is 2, it has exactly one bit. Thus, this means that when you are OR with a character, and this leads to a certain result, there are exactly 2 ^ 1 different characters that could lead to such a result.
Anyway, my question is, can this trick somehow extend to characters with differences not multiple of 2? For example, if I had characters #and 0(by the way, they have a difference of 13), is there any bit-twisting hack that I could use to check if any of them are char, without branching?
Thank you for your help.
edit: , .NET Framework, char.IsLetter. , a - A == 97 - 65 == 32, OR 0x20 char ( ToUpper).