Fix Long.bitCount. Fix #413

This commit is contained in:
Alexey Andreev 2019-08-07 18:48:06 +03:00
parent dcd1f64c81
commit ec9fe5471d
2 changed files with 19 additions and 6 deletions

View File

@ -312,12 +312,12 @@ public class TLong extends TNumber implements TComparable<TLong> {
} }
public static int bitCount(long i) { public static int bitCount(long i) {
i = ((i & 0xAAAAAAAAAAAAAAAAL) >> 1) + (i & 0x5555555555555555L); i = ((i & 0xAAAAAAAAAAAAAAAAL) >>> 1) + (i & 0x5555555555555555L);
i = ((i & 0xCCCCCCCCCCCCCCCCL) >> 2) + (i & 0x3333333333333333L); i = ((i & 0xCCCCCCCCCCCCCCCCL) >>> 2) + (i & 0x3333333333333333L);
i = ((i & 0x3030303030303030L) >> 4) + (i & 0x0303030303030303L); i = ((i & 0x7070707070707070L) >>> 4) + (i & 0x0707070707070707L);
i = ((i & 0x0700070007000700L) >> 8) + (i & 0x0007000700070007L); i = ((i & 0x0F000F000F000F00L) >>> 8) + (i & 0x000F000F000F000FL);
i = ((i & 0x000F0000000F0000L) >> 16) + (i & 0x0000000F0000000FL); i = ((i & 0x001F0000001F0000L) >>> 16) + (i & 0x0000001F0000001FL);
i = ((i & 0x0000001F00000000L) >> 32) + (i & 0x000000000000001FL); i = ((i & 0x0000003F00000000L) >>> 32) + (i & 0x000000000000003FL);
return (int) i; return (int) i;
} }

View File

@ -52,4 +52,17 @@ public class LongTest {
assertEquals(0xFFFFFFFFFFFFFFFFL, Long.reverse(0xFFFFFFFFFFFFFFFFL)); assertEquals(0xFFFFFFFFFFFFFFFFL, Long.reverse(0xFFFFFFFFFFFFFFFFL));
assertEquals(0xF63BA00000000000L, Long.reverse(0x5DC6F)); assertEquals(0xF63BA00000000000L, Long.reverse(0x5DC6F));
} }
@Test
public void bitsCounted() {
assertEquals(39, Long.bitCount(2587208649207147453L));
assertEquals(0, Long.bitCount(0));
assertEquals(64, Long.bitCount(-1));
assertEquals(6, Long.bitCount(12345));
assertEquals(59, Long.bitCount(-12345));
for (int i = 0; i < 64; ++i) {
assertEquals(1, Long.bitCount(1L << i));
}
}
} }