For an assignment, I\'m trying to make some code in C that uses only bit manipulation to test if an integer is an ASCII uppercase letter. The letter will be given by its ASCII c
... to see if a letter is uppercase
Simplification:
Let us assume ranges [A-Z] and [a-z] char
differ by the same value which is a power of 2. So 'B'-'b'
equals 'X'-'x'
, etc.
#define CASE_MASK ('A' ^ 'a')
// Is letter uppercase?
int is_letter_upper(int ch) {
return (ch & CASE_MASK) == ('A' & CASE_MASK);
}
// Is letter lowercase?
int is_letter_lower(int ch) {
return (ch & CASE_MASK) == ('a' & CASE_MASK);
}
This works for ASCII and EBCIDIC
A more "bit manipulation" answer
int is_letter_upperBM(int ch) {
return !((ch & CASE_MASK) ^ ('A' & CASE_MASK));
}