From ec9fe5471dfc7c7e346cda5718fac41954798964 Mon Sep 17 00:00:00 2001 From: Alexey Andreev Date: Wed, 7 Aug 2019 18:48:06 +0300 Subject: [PATCH] Fix Long.bitCount. Fix #413 --- .../java/org/teavm/classlib/java/lang/TLong.java | 12 ++++++------ .../java/org/teavm/classlib/java/lang/LongTest.java | 13 +++++++++++++ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/classlib/src/main/java/org/teavm/classlib/java/lang/TLong.java b/classlib/src/main/java/org/teavm/classlib/java/lang/TLong.java index 8c38bae93..eca1c5c85 100644 --- a/classlib/src/main/java/org/teavm/classlib/java/lang/TLong.java +++ b/classlib/src/main/java/org/teavm/classlib/java/lang/TLong.java @@ -312,12 +312,12 @@ public class TLong extends TNumber implements TComparable { } public static int bitCount(long i) { - i = ((i & 0xAAAAAAAAAAAAAAAAL) >> 1) + (i & 0x5555555555555555L); - i = ((i & 0xCCCCCCCCCCCCCCCCL) >> 2) + (i & 0x3333333333333333L); - i = ((i & 0x3030303030303030L) >> 4) + (i & 0x0303030303030303L); - i = ((i & 0x0700070007000700L) >> 8) + (i & 0x0007000700070007L); - i = ((i & 0x000F0000000F0000L) >> 16) + (i & 0x0000000F0000000FL); - i = ((i & 0x0000001F00000000L) >> 32) + (i & 0x000000000000001FL); + i = ((i & 0xAAAAAAAAAAAAAAAAL) >>> 1) + (i & 0x5555555555555555L); + i = ((i & 0xCCCCCCCCCCCCCCCCL) >>> 2) + (i & 0x3333333333333333L); + i = ((i & 0x7070707070707070L) >>> 4) + (i & 0x0707070707070707L); + i = ((i & 0x0F000F000F000F00L) >>> 8) + (i & 0x000F000F000F000FL); + i = ((i & 0x001F0000001F0000L) >>> 16) + (i & 0x0000001F0000001FL); + i = ((i & 0x0000003F00000000L) >>> 32) + (i & 0x000000000000003FL); return (int) i; } diff --git a/tests/src/test/java/org/teavm/classlib/java/lang/LongTest.java b/tests/src/test/java/org/teavm/classlib/java/lang/LongTest.java index 0e7b004bb..af3aa1b3b 100644 --- a/tests/src/test/java/org/teavm/classlib/java/lang/LongTest.java +++ b/tests/src/test/java/org/teavm/classlib/java/lang/LongTest.java @@ -52,4 +52,17 @@ public class LongTest { assertEquals(0xFFFFFFFFFFFFFFFFL, Long.reverse(0xFFFFFFFFFFFFFFFFL)); 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)); + } + } }