Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 292
Josh Morrison Avatar asked Jan 26 '11 03:01

Josh Morrison


People also ask

How do you find most significant bit C?

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.

How do you isolate the most significant bit?

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.

How do you read a bit?

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.


1 Answers

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.

like image 136
R.. GitHub STOP HELPING ICE Avatar answered Sep 19 '22 15:09

R.. GitHub STOP HELPING ICE