Search code examples
cbitwise-operators

What is the most portable way to read and write the highest bit of an integer in C?


What is the most portable way to read and write the highest bit of an integer in C?

This is a Bloomberg interview question. I didn’t give best answer at that time. Can anyone please answer it?


Solution

  • If the type is unsigned, it's easy:

    (type)-1-(type)-1/2
    

    For signed values, I know no way. If you find a way, it would answer several unanswered questions on SO:

    C question: off_t (and other signed integer types) minimum and maximum values

    Is there any way to compute the width of an integer type at compile-time?

    Maybe others.