0

I want to find a bit mask with only first bit set to 1 but mask length has to be determined dynamically taking in consideration number n.

For example if n = 161
161 in binary format is 10100001
Determined mask should be 10000000

So it can be compared like this:

10100001
10000000

Second example, n = 34
34 in binary format is 100010
Determined mask should be 100000
So it can be compared like this:

100010
100000

There is certainly mathematical solution to this and maybe even purely by moving bits around but I can't find solution in any of the two ways, so any help is appreciated.

Thank you.

toni rmc
  • 848
  • 2
  • 10
  • 25
  • No language tag? There are fairly general ways, but for example Java has [Integer.highestOneBit](https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#highestOneBit(int)) – harold Nov 04 '17 at 21:39
  • Solution should be mathematical or by moving bits which is language agnostic. I'm not looking for some X language obscure feature which has this implemented. I want to know process of getting there by myself. – toni rmc Nov 04 '17 at 21:43
  • 1
    So like [this](https://stackoverflow.com/a/53184/555045)? – harold Nov 04 '17 at 21:47
  • @harold yes, accepted answer works, indeed clever solution but maybe (probably is) more efficient way than shifting bit by 1 to the right in the n and by 1 to the left in the mask in the same loop? – toni rmc Nov 04 '17 at 22:09
  • 1
    Yes, I linked to the second answer intentionally, the accepted one is just the naive way to do it while the second one is a log-step trick in general (for broadword computation). – harold Nov 04 '17 at 22:14
  • That is it. Log step trick is just an answer I was looking for. Thanks. – toni rmc Nov 07 '17 at 16:09

0 Answers0