与那些数目可变填写 [英] Fill with variable number of ones
本文介绍了与那些数目可变填写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是充满未知的变量(在编译时)的人的数量的最好方法?例如,假设:
What's the best way to fill a variable with an unknown (at compile time) number of ones? For example, let's say:
int n = 5;
int b = fillwithones(5);
现在B包含11111(二进制)。
now b contains 11111 (in binary).
我不能就这么难code INT B = 31,因为n不事先已知的(在我的应用程序)。
I can't just hard code int b = 31 because n is not known ahead of time (in my application).
我可以做这样的事情:
int b = pow(2, n) - 1
但是,使用战俘似乎很浪费的。
But using a pow seems very wasteful.
谢谢!
推荐答案
您可以使用左移,然后减去1:
You can use left shift and then subtract 1:
unsigned int b = (1U << n) - 1U;
// Broken down into steps
// 1 = 00000001b
// 1 << 5 = 00100000b
// (1 << 5) - 1 = 00011111b
这部作品的原因是的 1左移n次的是一样的 2 N 的,因为每个唯一位的位置重新presents 2的幂。
The reason this works is 1 shifted left n times is the same as 2n, as each sole bit position represents a power of 2.
这篇关于与那些数目可变填写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文