Tuesday, February 23, 2016

Number of bits needed to represent an integer

The following C# function calculates the number of bits that are needed to represent a random integer number.

int NumberOfBits(int number)
{
    var bits = 1;

    while ((number >>= 1) != 0)
    {
        bits++;
    }

    return bits;
}

No comments:

Post a Comment