Fill with variable number of ones

后端 未结 2 1882
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  无人及你
    2021-01-06 07:21

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

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

提交回复
热议问题