Fill with variable number of ones

此生再无相见时 提交于 2019-11-30 18:18:24

问题


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

now b contains 11111 (in binary).

I can't just hard code int b = 31 because n is not known ahead of time (in my application).

I could do something like this:

int b = pow(2, n) - 1

But using a pow seems very wasteful.

Thanks!


回答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

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.




回答2:


A funny way to get the highest bits as 1 and the lowest bits as zero is using this nice trick:

#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.



来源:https://stackoverflow.com/questions/7919513/fill-with-variable-number-of-ones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!