From 874371ea3a5ca7a4366cbe54bf8b0a77bf31894b Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Mon, 20 Jan 2014 04:04:12 +0100 Subject: m + counting bits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Mattias Andrée --- src/algorithms/bits/Bits.java | 81 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 80 insertions(+), 1 deletion(-) (limited to 'src/algorithms/bits/Bits.java') diff --git a/src/algorithms/bits/Bits.java b/src/algorithms/bits/Bits.java index 4a08d05..0930b19 100644 --- a/src/algorithms/bits/Bits.java +++ b/src/algorithms/bits/Bits.java @@ -22,7 +22,32 @@ package algorithms.bits; */ public class Bits { -£>for T in char byte short int long; do +£} + + /** + * Lookup table for the number of set bits in a byte + */ + private static byte[] ONES_TABLE_256 = { £(table 4 0) }; + /* ONES_TABLE_256[0] = 0; + * for (int i = 0; i < 256; i++) + * ONES_TABLE_256[i] = (i & 1) + ONES_TABLE_256[i / 2]; + */ + + +£S=${T_S#*_} /** * Sets or clears individual bits in an integer * @@ -61,6 +86,60 @@ public class Bits { return (£{T})(zero ^ ((£{T})(zero ^ one) & mask)); } + + /** + * Clears the least significant bit set + * + * @param value The integer + * @return The value with its least significant set bit cleared + */ + public static £{T} clearLeastSignificant(£{T} value) + { + return (£{T})(value & (value - 1)); + } + + /** + * Calculate the number of set bits in an integer, naïve version + * + * @param value The integer + * @return The number of set bits + */ + public static £{T} ones_naïve(£{T} value) + { + £{T} count = 0; + for (; value != 0; value >>>= 1) + count += (£{T})(value & 1); + return count; + } + + /** + * Calculate the number of set bits in an integer, Wegner's version + * + * @param value The integer + * @return The number of set bits + */ + public static £{T} ones_wegner(£{T} value) + { + £{T} count = 0; + for (; value != 0; count++) + value &= value - 1; /* clear the least significant bit set */ + return count; + } + + /** + * Calculate the number of set bits in an integer, partial lookup table version + * + * @param value The integer + * @return The number of set bits + */ + public static £{T} ones_table(£{T} value) + { +£> $1) & 255)]" +£>} + return (£{T})((£{T})(£(lookup 0) + £(lookup 8)) + (£{T})(£(lookup 16) + £(lookup 24))); + /* In C you can split the value by getting the address of the value and cast the pointer to char* */ + } £>done } -- cgit v1.2.3-70-g09d2