From 4cb075b1683434566580fc5152d660cf2e363e96 Mon Sep 17 00:00:00 2001 From: Chocobo1 Date: Wed, 9 Feb 2022 18:30:05 +0800 Subject: [PATCH] Use "table look-up" method for reversing byte This method takes constant time and is less prone to (CPU) pipeline stalling due to less computation. Also it is slightly faster than the previous method. --- src/base/bittorrent/ltqbitarray.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/base/bittorrent/ltqbitarray.cpp b/src/base/bittorrent/ltqbitarray.cpp index 940c3f8ce..7a2c109f8 100644 --- a/src/base/bittorrent/ltqbitarray.cpp +++ b/src/base/bittorrent/ltqbitarray.cpp @@ -37,8 +37,18 @@ namespace { unsigned char reverseByte(const unsigned char byte) { - // https://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64Bits - return (((byte * 0x80200802ULL) & 0x0884422110ULL) * 0x0101010101ULL) >> 32; + // https://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable + static const unsigned char table[] = + { +#define R2(n) n, (n + (2 * 64)), (n + 64), (n + (3 * 64)) +#define R4(n) R2(n), R2(n + (2 * 16)), R2(n + 16), R2(n + (3 * 16)) +#define R6(n) R4(n), R4(n + (2 * 4)), R4(n + 4), R4(n + (3 * 4)) + R6(0), R6(2), R6(1), R6(3) +#undef R6 +#undef R4 +#undef R2 + }; + return table[byte]; } }