find the index of the highest bit set of a 32-bit number without loops obviously

前端 未结 11 1383
梦毁少年i
梦毁少年i 2021-01-07 01:56

Here\'s a tough one(atleast i had a hard time :P):

find the index of the highest bit set of a 32-bit number without using any loops.

11条回答
  •  南方客
    南方客 (楼主)
    2021-01-07 02:26

    You could do it like this (not optimised):

    int index = 0;
    uint32_t temp = number;
    
    if ((temp >> 16) != 0) {
        temp >>= 16;
        index += 16;
    }
    
    if ((temp >> 8) != 0) {
        temp >>= 8
        index += 8;
    }
    
    ...
    

提交回复
热议问题