向上舍入到2的下一个幂 [英] Rounding up to next power of 2

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

问题描述

我想编写一个函数,该函数返回2的最接近的下一个幂.例如,如果我的输入为789,则输出应为1024.是否有任何方法可以在不使用任何循环而仅使用一些按位运算符的情况下实现这一目标?

I want to write a function that returns the nearest next 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?

推荐答案

检查位扭曲的黑客.您需要获取以2为底的对数,然后将其加1. 32位值的示例:

Check the Bit Twiddling Hacks. You need to get the base 2 logarithm, then add 1 to that. Example for a 32-bit value:

向上舍入为2的下一个最高幂

Round up to the next highest power of 2

unsigned int v; // compute the next highest power of 2 of 32-bit v

v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;

对其他宽度的扩展应该很明显.

The extension to other widths should be obvious.

这篇关于向上舍入到2的下一个幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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