I have two tasks for an assignment, one return the number of bits in type int on any machine. I thought I would write my function like so:
int CountIntBitsF() {
In limits.h
, UINT_MAX is the maximum value for an object of type unsigned int. Which means it is an int with all bits set to 1. So, counting the number of bits in an int:
#include
int intBits () {
int x = INT_MAX;
int count = 2; /* start from 1 + 1 because we assume
* that sign uses a single bit, which
* is a fairly reasonable assumption
*/
/* Keep shifting bits to the right until none is left.
* We use divide instead of >> here since I personally
* know some compilers which does not shift in zero as
* the topmost bit
*/
while (x = x/2) count++;
return count;
}