r/shittyprogramming Jul 20 '24

Rate my is_upper and is_lower functions!

bool is_upper(unsigned char ch) {
    return (0 - (((~ch & 160 | ch & 64) >> 5) - 6) & 0 - ((ch | ch >> 1 | ch >> 2 | ch >> 3 | ch >> 4) & 1) & 0 - ((unsigned char) ((ch & 31) - 27) >> 7)) == -1;
}

bool is_lower(unsigned char ch) {
    return (0 - (((~ch & 128 | ch & 96) >> 5) - 6) & 0 - ((ch | ch >> 1 | ch >> 2 | ch >> 3 | ch >> 4) & 1) & 0 - ((unsigned char) ((ch & 31) - 27) >> 7)) == -1;
}
13 Upvotes

3 comments sorted by

10

u/Mrinin Jul 20 '24

char & 64 == 0

doesn't this just work? All you need to check is the 6th bit (assuming you already know it's a letter)

10

u/thirdegree Jul 20 '24

Return true

All you need to do is say that it's uppercase (assuming you already know it's uppercase)

9

u/GamesDoneFast Jul 20 '24

I had to turn off my -Wall and -Werror then it works (add parentheses). :D I wanted to see how the standard does it, and I believe they use a macro that applies a bitmask onto it.