求Julia中小于n的2的次幂

求Julia中小于n的2的次幂,julia,Julia,我需要在Julia中找到小于给定数字的二次幂 i、 e.smallerpoweroftwo(15)应返回8,但smallerpoweroftwo(17)应返回16 到目前为止,我已经有了这一点,但对我来说,在一串比特中搜索似乎有点不方便。也许不是。。。有什么想法吗 function smallerpoweroftwo(n::Int) 2^(length(bits(n)) - search(bits(n), '1')) end 谢谢 编辑: 我主要是在想,是否有一种更优雅的方法,仅仅使用

我需要在Julia中找到小于给定数字的二次幂

i、 e.
smallerpoweroftwo(15)
应返回
8
,但
smallerpoweroftwo(17)
应返回
16

到目前为止,我已经有了这一点,但对我来说,在一串比特中搜索似乎有点不方便。也许不是。。。有什么想法吗

function smallerpoweroftwo(n::Int)
    2^(length(bits(n)) - search(bits(n), '1'))
end
谢谢

编辑: 我主要是在想,是否有一种更优雅的方法,仅仅使用位运算就可以做到这一点。或者在某些其他语言中有类似的位长函数吗?

这个怎么样?1



1在jverzani的评论之后,在解决方案中添加了指数

Julia的标准库具有
prevpow2
nextpow2
功能:

help?> prevpow2
search: prevpow2 prevpow prevprod

  prevpow2(n)

  The largest power of two not greater than n. Returns 0 for n==0, and returns -prevpow2(-n) for negative
  arguments.

help?> nextpow2
search: nextpow2 nextpow nextprod

  nextpow2(n)

  The smallest power of two not less than n. Returns 0 for n==0, and returns -nextpow2(-n) for negative
  arguments.
prevpow2
函数应该做你想做的事情。

我认为:
f(x)=2^(floor(Int,log2(x))
是他们想要的,有了
2^
部分。
help?> prevpow2
search: prevpow2 prevpow prevprod

  prevpow2(n)

  The largest power of two not greater than n. Returns 0 for n==0, and returns -prevpow2(-n) for negative
  arguments.

help?> nextpow2
search: nextpow2 nextpow nextprod

  nextpow2(n)

  The smallest power of two not less than n. Returns 0 for n==0, and returns -nextpow2(-n) for negative
  arguments.