巧妙地在Python中返回最近的"floor"二进制数?

3 python binary numpy

寻找以下内容:

t = 1
get_floor_bin(t)
#1

t = 2
get_floor_bin(t)
#2

t = 3
get_floor_bin(t)
#2

t = 7
get_floor_bin(t)
#4

t = 15
get_floor_bin(t)
#8

t = 16
get_floor_bin(t)
#16
Run Code Online (Sandbox Code Playgroud)

我目前的方法是创建一个二进制数列表,并在列表中搜索每个最近的楼层号,但我想知道是否有更聪明的方法.

谢谢!

hol*_*web 18

这是你需要的吗?你的解释并不容易理解.

for i in 1, 2, 3, 7, 15, 16:
    print 1 << (i.bit_length() - 1)
Run Code Online (Sandbox Code Playgroud)

这给出了:

1
2
2
4
8
16
Run Code Online (Sandbox Code Playgroud)