aboutsummaryrefslogtreecommitdiffstats
path: root/include
diff options
context:
space:
mode:
Diffstat (limited to 'include')
-rw-r--r--include/bit_ops.h64
1 files changed, 58 insertions, 6 deletions
diff --git a/include/bit_ops.h b/include/bit_ops.h
index 41c401028..42b922620 100644
--- a/include/bit_ops.h
+++ b/include/bit_ops.h
@@ -11,13 +11,65 @@
namespace Botan {
/*************************************************
-* Simple Bit Manipulation *
+* Return true iff arg is 2**n for some n > 0 *
+* T should be an unsigned integer type *
+*
*************************************************/
-bool power_of_2(u64bit);
-u32bit high_bit(u64bit);
-u32bit low_bit(u64bit);
-u32bit significant_bytes(u64bit);
-u32bit hamming_weight(u64bit);
+template<typename T>
+inline bool power_of_2(T arg)
+ {
+ return ((arg != 0 && arg != 1) && ((arg & (arg-1)) == 0));
+ }
+
+/*************************************************
+* Return the index of the highest set bit
+* T is an unsigned integer type
+*************************************************/
+template<typename T>
+inline u32bit high_bit(T n)
+ {
+ for(u32bit i = 8*sizeof(T); i > 0; --i)
+ if((n >> (i - 1)) & 0x01)
+ return i;
+ return 0;
+ }
+
+/*************************************************
+* Return the index of the lowest set bit *
+*************************************************/
+template<typename T>
+inline u32bit low_bit(T n)
+ {
+ for(u32bit i = 0; i != 8*sizeof(T); ++i)
+ if((n >> i) & 0x01)
+ return (i + 1);
+ return 0;
+ }
+
+/*************************************************
+* Return the number of significant bytes in n *
+*************************************************/
+template<typename T>
+inline u32bit significant_bytes(T n)
+ {
+ for(u32bit j = 0; j != sizeof(T); ++j)
+ if(get_byte(j, n))
+ return sizeof(T)-j;
+ return 0;
+ }
+
+/*************************************************
+* Return the Hamming weight of n *
+*************************************************/
+template<typename T>
+inline u32bit hamming_weight(T n)
+ {
+ u32bit weight = 0;
+ for(u32bit j = 0; j != 8*sizeof(T); ++j)
+ if((n >> j) & 0x01)
+ ++weight;
+ return weight;
+ }
}