回合的两个最近的电源 [英] Round to the nearest power of two

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

问题描述

有一个行前pression(可能布尔),以获得最近的2 ^ n个对于一个给定的整数??

Is there a one line expression (possibly boolean) to get the nearest 2^n number for a given integer??

例:5,6,7必须是8

Example: 5,6,7 must be 8

感谢

推荐答案

四舍五入到2的下一个更高的功率:看的位摆弄黑客的。

Round up to the next higher power of two: see bit-twiddling hacks.

在C:

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++;

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

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