/** * Dirk Bosman's fully unraveled binary search method. * Calculate how many bits wide a number is, * i.e. position of highest 1 bit. * @return p where 2**p is first power of two >= n. * e.g. binary 0001_0101 -> 5, 0xffffffff -> 32, * 0 -> 0, 1 -> 1, 2 -> 2, 3 -> 2, 4 -> 3 */ public static final int widthInBits ( int n ) { switch ( n ) { case Integer.MIN_VALUE .. -1 : return 32 ; case 0: return 0; case 1: return 1; case 0x2 .. 0x3: return 2; case 0x4 .. 0x7: return 3; case 0x8 .. 0xf: return 4; case 0x10 .. 0x1f: return 5; case 0x20 .. 0x3f: return 6; case 0x40 .. 0x7f: return 7; case 0x80 .. 0xff: return 8; case 0x100 .. 0x1ff: return 9; case 0x200 .. 0x3ff: return 10; case 0x400 .. 0x7ff: return 11; case 0x800 .. 0xfff: return 12; case 0x1000 .. 0x1fff: return 13; case 0x2000 .. 0x3fff: return 14; case 0x4000 .. 0x7fff: return 15; case 0x8000 .. 0xffff: return 16; case 0x10000 .. 0x1ffff: return 17; case 0x20000 .. 0x3ffff: return 18; case 0x40000 .. 0x7ffff: return 19; case 0x80000 .. 0xfffff: return 20; case 0x100000 .. 0x1fffff: return 21; case 0x200000 .. 0x3fffff: return 22; case 0x400000 .. 0x7fffff: return 23; case 0x800000 .. 0xffffff: return 24; case 0x1000000 .. 0x1ffffff : return 25 ; case 0x2000000 .. 0x3ffffff : return 26 ; case 0x4000000 .. 0x7ffffff : return 27 ; case 0x8000000 .. 0xfffffff : return 28 ; case 0x10000000 .. 0x1fffffff : return 29 ; case 0x20000000 .. 0x3fffffff : return 30 ; case 0x40000000 .. 0x7fffffff : return 31 ; } }