舍入到2最近的电源 [英] Rounding up to nearest power of 2

查看:141
本文介绍了舍入到2最近的电源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个返回的2号最近上电源的功能。例如,如果我输入789,输出应该是1024是否有实现这一目标而无需使用任何循环只是使用一些位操作的方法吗?

I want to write a function that returns the nearest upper power of 2 number. For example if my input is 789, the output should be 1024. Is there any way of achieving this without using any loops but just using some bitwise operators?

推荐答案

检查位twidding黑客的。你需要得到基地2的对数,再加入1到这一点。

Check the Bit twidding hacks. You need to get the base 2 logarithm, then add 1 to that.

这篇关于舍入到2最近的电源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆