Search code examples
cinteger-overflowtwos-complement

How to test the most significant bit of signed or unsigned integer?


Given a clock_t data type that is guaranteed to be an integer of some sort, how do you test the value of the most significant bit using portable C code? In other words, I need the definition of this function:

bool is_msb_set(clock_t clock);

But here's the twist: you don't know the size of clock_t nor if it is signed or unsigned (but assumed "signed" is twos-compliment).

My first thought was to do this:

const clock_t MSB = 1 << ((sizeof(clock_t) * 8) - 1);

bool is_msb_set(clock_t value) {
    return value & MSB;
}

but the definition of MSB overflows if clock_t is a signed value. Maybe I'm overthinking this, but I'm stumped.


Solution

  • I think we can first check whether clock_t is signed or unsigned, and proceed accordingly.

    bool is_msb_set(clock_t value) {
        if ((clock_t)-1 < 0) {
            /* clock_t is signed */
            return value < 0;
        } else {
            /* clock_t is unsigned */
            return ((value << 1) >> 1) ^ value;
        }
    }