2 previous电源电源、previous

2023-09-11 00:08:39 作者:依然、为你疯狂℡

对于如何找到2给定值的下一个动力大量的信息(见参考文献),但我找不到任何让两人的previous力量。

There is a lot of information on how to find the next power of 2 of a given value (see refs) but I cannot find any to get the previous power of two.

我觉得到目前为止,唯一的办法是保持一个表,两个高达2 ^ 64的所有权力,并做一个简单的查询。

The only way I find so far is to keep a table with all power of two up to 2^64 and make a simple lookup.

Acius片段 gamedev 位操作黑客 Stack溢出 Acius' Snippets gamedev Bit Twiddling Hacks Stack Overflow

推荐答案

这是我目前的解决办法找到两个任意给定的正整数n的,也是一个小的功能,下一个和previous权力,以确定数字是两个力量。

This is my current solution to find the next and previous powers of two of any given positive integer n and also a small function to determine if a number is power of two.

这是实现对Ruby。

class Integer

  def power_of_two?
    (self & (self - 1) == 0)
  end

  def next_power_of_two
    return 1 if self <= 0
    val = self
    val = val - 1
    val = (val >> 1) | val
    val = (val >> 2) | val
    val = (val >> 4) | val
    val = (val >> 8) | val
    val = (val >> 16) | val
    val = (val >> 32) | val if self.class == Bignum
    val = val + 1
  end

  def prev_power_of_two
   return 1 if self <= 0
   val = self
   val = val - 1
   val = (val >> 1) | val
   val = (val >> 2) | val
   val = (val >> 4) | val
   val = (val >> 8) | val
   val = (val >> 16) | val
   val = (val >> 32) | val if self.class == Bignum
   val = val - (val >> 1)
  end
end

使用示例:

10.power_of_two? => false
16.power_of_two? => true
10.next_power_of_two => 16
10.prev_power_of_two => 8

有关两人的previous力量,找到下一个和除以二是比上面的方法稍微慢一些。

For the previous power of two, finding the next and dividing by two is slightly slower than the method above.

我不知道它是如何工作与大数。

I am not sure how it works with Bignums.