Advertisement
Iam_Sandeep

Find the largest power of 2 (most significant bit in binary form), which is less than or equal to th

Jun 13th, 2022
542
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.61 KB | None | 0 0
  1. def findMSB(n):
  2.     n=n | n>>1
  3.     n=n | n>>2
  4.     n=n | n>>4
  5.     n=n | n>>8
  6.     n=n | n>>16
  7.     n=n ^ n>>1
  8.     return n
  9. ```
  10. The first | makes sure the original top bit and the 2nd highest top bit are set. The second | makes sure those two, and the next two are, etc, until you potentially hit all 32 bits. Ie
  11.  
  12. 100010101 -> 111111111
  13.  
  14. Then we remove all but the top bit by xoring the string of 1's with that string of 1's shifted one to the left, and we end up with just the one top bit followed by 0's.
  15. link="https://thecodingbot.com/find-the-greatest-power-of-2-less-than-or-equal-to-a-given-number/"
  16. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement