Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Integer.highestOneBit in C#

I have been trying a lot to find an exact replacement for the Java's Integer.highestOneBit(int) in C#.

I even tried finding its source code but to no avail.

JavaDocs tells that this function:

Returns an int value with at most a single one-bit, in the position of the highest-order ("leftmost") one-bit in the specified int value.

So how would I go about implementing this in C#? Any help or link/redirection is appreciated.

like image 300
Nathan Avatar asked Dec 14 '22 16:12

Nathan


1 Answers

This site provides an implementation that should work in C# with a few modifications:

public static uint highestOneBit(uint i) 
{
    i |= (i >>  1);
    i |= (i >>  2);
    i |= (i >>  4);
    i |= (i >>  8);
    i |= (i >>  16);
    return i - (i >> 1);
}

http://ideone.com/oEiNcM

It basically fills all bit places lower than the highest one with 1s and then removes all except the highest bit.

Example (using only 16 bits instead of 32):

start: i =        0010000000000000
i |= (i >> 1)     0010000000000000 | 0001000000000000 -> 0011000000000000
i |= (i >> 2)     0011000000000000 | 0000110000000000 -> 0011110000000000
i |= (i >> 4)     0011110000000000 | 0000001111000000 -> 0011111111000000
i |= (i >> 8)     0011111111000000 | 0000000000111111 -> 0011111111111111
i - (i >> 1)      0011111111111111 - 0001111111111111 -> 0010000000000000
like image 140
JLRishe Avatar answered Dec 30 '22 17:12

JLRishe