Fill with variable number of ones

后端 未结 2 1878
隐瞒了意图╮
隐瞒了意图╮ 2021-01-06 07:11

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


        
2条回答
  •  梦毁少年i
    2021-01-06 07:42

    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.

提交回复
热议问题