-3

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
Bhadresh
  • 15
  • 3

2 Answers2

1

The method should return a number which represents a hex value for that number of bits set.

The problem is ambiguous as stated. Many numbers have the same 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.

No it isn't, it's 15, but 30 would also satisfy the requirement (11110), and so would 60, 120, ..., and also various numbers of binary form 10101010, 01010101, 110011, etc.

Similarly, when I pass 5 as parameter then the function should return 37 as (11111) = 37.

No it doesn't. 11111 is 31.

77 for 6 as parameter

Wrong again, it's 63.

and so on.

The problem is ambiguous as stated. Either you've left something out or it needs to be clarified at source.

And you haven't got one single binary->decimal conversion right. You need to review that. Or are you talking in octal?

user207421
  • 305,947
  • 44
  • 307
  • 483
0

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).

  • @user3139890 No problem, if this answered your question please accept my answer :) Thanks. –  Sep 14 '15 at 23:58