Fix Long.reverse

This commit is contained in:
Alexey Andreev 2018-11-23 14:32:50 +03:00
parent 3e152f4bb8
commit b9ec21a667
2 changed files with 20 additions and 6 deletions

View File

@ -329,12 +329,12 @@ public class TLong extends TNumber implements TComparable<TLong> {
} }
public static long reverse(long i) { public static long reverse(long i) {
i = ((i & 0xAAAAAAAAAAAAAAAAL) >> 1) | ((i & 0x5555555555555555L) << 1); i = ((i & 0xAAAAAAAAAAAAAAAAL) >>> 1) | ((i & 0x5555555555555555L) << 1);
i = ((i & 0xCCCCCCCCCCCCCCCCL) >> 2) | ((i & 0x3333333333333333L) << 2); i = ((i & 0xCCCCCCCCCCCCCCCCL) >>> 2) | ((i & 0x3333333333333333L) << 2);
i = ((i & 0xF0F0F0F0F0F0F0F0L) >> 4) | ((i & 0x0F0F0F0F0F0F0F0FL) << 4); i = ((i & 0xF0F0F0F0F0F0F0F0L) >>> 4) | ((i & 0x0F0F0F0F0F0F0F0FL) << 4);
i = ((i & 0xFF00FF00FF00FF00L) >> 8) | ((i & 0x00FF00FF00FF00FFL) << 8); i = ((i & 0xFF00FF00FF00FF00L) >>> 8) | ((i & 0x00FF00FF00FF00FFL) << 8);
i = ((i & 0xFFFF0000FFFF0000L) >> 16) | ((i & 0x0000FFFF0000FFFFL) << 16); i = ((i & 0xFFFF0000FFFF0000L) >>> 16) | ((i & 0x0000FFFF0000FFFFL) << 16);
i = ((i & 0xFFFF0000FFFF0000L) >> 32) | ((i & 0x0000FFFF0000FFFFL) << 32); i = ((i & 0xFFFFFFFF00000000L) >>> 32) | ((i & 0x00000000FFFFFFFFL) << 32);
return i; return i;
} }

View File

@ -38,4 +38,18 @@ public class LongTest {
public void calculatesHashCode() { public void calculatesHashCode() {
assertEquals(23 ^ 42, Long.hashCode((23L << 32) | 42)); assertEquals(23 ^ 42, Long.hashCode((23L << 32) | 42));
} }
@Test
public void bitsReversed() {
assertEquals(0, Long.reverse(0));
assertEquals(0x8000000000000000L, Long.reverse(1));
assertEquals(0x0020000000000000L, Long.reverse(0x400));
assertEquals(0x0000000000000001L, Long.reverse(0x8000000000000000L));
assertEquals(0x8888888888888888L, Long.reverse(0x1111111111111111L));
assertEquals(0x0C0C0C0C0C0C0C0CL, Long.reverse(0x3030303030303030L));
assertEquals(0x00000000000000FFL, Long.reverse(0xFF00000000000000L));
assertEquals(0xFF00000000000000L, Long.reverse(0x00000000000000FFL));
assertEquals(0xFFFFFFFFFFFFFFFFL, Long.reverse(0xFFFFFFFFFFFFFFFFL));
assertEquals(0xF63BA00000000000L, Long.reverse(0x5DC6F));
}
} }