What's the best way to fill a variable with an unknown (at compile time) number of ones? For example, let's say:
用未知(在编译时)的1个数填充变量的最好方法是什么?例如,让我们说:
int n = 5;
int b = fillwithones(5);
now b contains 11111 (in binary).
现在b包含11111(二进制)。
I can't just hard code int b = 31 because n is not known ahead of time (in my application).
我不能只对int b = 31进行硬编码,因为(在我的应用程序中)不提前知道n。
I could do something like this:
我可以这样做:
int b = pow(2, n) - 1
But using a pow seems very wasteful.
但是使用pow似乎非常浪费。
Thanks!
谢谢!
2 个解决方案
#1
17
You can use left shift and then subtract 1:
你可以用左移然后减去1:
unsigned int b = (1U << n) - 1U;
// Broken down into steps
// 1 = 00000001b
// 1 << 5 = 00100000b
// (1 << 5) - 1 = 00011111b
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.
这样做的原因是左移1次n乘以等于2n,因为每个单独的位代表2的幂。
#2
1
A funny way to get the highest bits as 1 and the lowest bits as zero is using this nice trick:
得到最高位为1,最低位为0的有趣方法是使用这个很好的技巧:
#include <limits.h>
...
int b = INT_MIN >> n;
This works because shift left operation on a negative number will mantain the sign of the operation, and since INT_MIN is 10000....0000 shifting it by n to the left will give you n bits to 1, but on the other side.
这个作品,因为左移位操作在一个负数将基本的符号操作,因为INT_MIN 10000 ....0000将它向左平移n个比特就会得到n个比特的1,但是在另一边。
#1
17
You can use left shift and then subtract 1:
你可以用左移然后减去1:
unsigned int b = (1U << n) - 1U;
// Broken down into steps
// 1 = 00000001b
// 1 << 5 = 00100000b
// (1 << 5) - 1 = 00011111b
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.
这样做的原因是左移1次n乘以等于2n,因为每个单独的位代表2的幂。
#2
1
A funny way to get the highest bits as 1 and the lowest bits as zero is using this nice trick:
得到最高位为1,最低位为0的有趣方法是使用这个很好的技巧:
#include <limits.h>
...
int b = INT_MIN >> n;
This works because shift left operation on a negative number will mantain the sign of the operation, and since INT_MIN is 10000....0000 shifting it by n to the left will give you n bits to 1, but on the other side.
这个作品,因为左移位操作在一个负数将基本的符号操作,因为INT_MIN 10000 ....0000将它向左平移n个比特就会得到n个比特的1,但是在另一边。