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

前端 未结 11 1376
梦毁少年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:20

    int high_bit_set(int n, int pos)
    {
    if(pos<0) 
    return -1;
    else
    return (0x80000000 & n)?pos:high_bit_set((n<<1),--pos);
    }
    
    main()
    {
    int n=0x23;
    int high_pos = high_bit_set(n,31);
    printf("highest index = %d",high_pos);
    }
    

    From your main call function high_bit_set(int n , int pos) with the input value n, and default 31 as the highest position. And the function is like above.

提交回复
热议问题