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

后端 未结 7 1345
忘掉有多难
忘掉有多难 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:02

    I would answer by saying no one should write that in pure C. Especially in an embedded environment. If the chipset does not provide a feature to count the number of leading zeros in a word, then it's probably pretty old, and certainly not something you want to be using. If it does, you would want to use that feature.

    As an example of a non-standard way to round an unsigned integer up to a power of two (you really need to clarify the type of the argument, as "number" is ambiguous) using gcc, you could do:

    unsigned
    round_up( unsigned x )
    {
        if( x < 2 ) {
            return 1U;
        } else {
            return 1U << ( CHAR_BIT * sizeof x - __builtin_clz( x - 1 ));
        }
    }
    

提交回复
热议问题