Write a C function that round up a number to next power of 2

后端 未结 7 1349
忘掉有多难
忘掉有多难 2021-01-04 12:53

I got the following question in an interview: \"Write a C function that round up a number to next power of 2.\"

I wrote the following answer:

#includ         


        
7条回答
  •  臣服心动
    2021-01-04 13:07

    In contrast to what others have said, the bit-twiddling trick actually can be used on any number of bits portably. Just change it a bit:

    unsigned int shift = 1;
    
    for (v--; shift < 8 * sizeof v; shift <<= 1)
    {
        v |= v >> shift;
    }
    
    return ++v;
    

    I believe any compiler will optimize the loop away, so it should be the same performence-wise (plus I think it looks better).

提交回复
热议问题