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?
To get MSB of the number, move first bit of 1 to highest order. Left shift 1 bits - 1 times and store result in some variable say msb = 1 << (bits - 1) . If bitwise AND operation num & msb evaluate to 1 then MSB of num is set otherwise not.
A simple solution is to one by one divide n by 2 until it becomes 0 and increment a count while doing this. This count actually represents the position of MSB.
To read a bit at a specific position, you must mask out all other bits in the value. The operator that assists in that process is the bitwise & (and). After you mask out all the other bits, the value that remains is either zero or some other value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With