Search code examples
c++bitset

Get octal value when n bits set


I want to create a method in C++ which will take a number as parameter. The method should return a number which represents an octal value for that number of bits set.

Example: If I pass 4 as parameter then the function should return 17 because for bits set to true (1111) = 17. Similarly, when I pass 5 as parameter then the function should return 37 as (11111) = 37. 77 for 6 as parameter and so on.


Solution

  • You can use the the left-shift operator and the fact that 2^(n)-1 is a bit string of n-1 1s.

    unsigned long long HexFunc(unsigned long long val)
    {
       return (1 << val) - 1;
    }
    

    This works because the left-shift operator for integers is equivalent to multiplying an integer by two (assuming no round off occurs). Thus 1 << val is essentially 2^(n).