Botan 1.10.17

bit_ops.h
Go to the documentation of this file.
1 /*
2 * Bit/Word Operations
3 * (C) 1999-2008 Jack Lloyd
4 *
5 * Distributed under the terms of the Botan license
6 */
7
8 #ifndef BOTAN_BIT_OPS_H__
9 #define BOTAN_BIT_OPS_H__
10
11 #include <botan/types.h>
12
13 namespace Botan {
14
15 /**
16 * Power of 2 test. T should be an unsigned integer type
17 * @param arg an integer value
18 * @return true iff arg is 2^n for some n > 0
19 */
20 template<typename T>
21 inline bool power_of_2(T arg)
22 {
23 return ((arg != 0 && arg != 1) && ((arg & (arg-1)) == 0));
24 }
25
26 /**
27 * Return the index of the highest set bit
28 * T is an unsigned integer type
29 * @param n an integer value
30 * @return index of the highest set bit in n
31 */
32 template<typename T>
33 inline size_t high_bit(T n)
34 {
35 for(size_t i = 8*sizeof(T); i > 0; --i)
36 if((n >> (i - 1)) & 0x01)
37 return i;
38 return 0;
39 }
40
41 /**
42 * Return the index of the lowest set bit
43 * T is an unsigned integer type
44 * @param n an integer value
45 * @return index of the lowest set bit in n
46 */
47 template<typename T>
48 inline size_t low_bit(T n)
49 {
50 for(size_t i = 0; i != 8*sizeof(T); ++i)
51 if((n >> i) & 0x01)
52 return (i + 1);
53 return 0;
54 }
55
56 /**
57 * Return the number of significant bytes in n
58 * @param n an integer value
59 * @return number of significant bytes in n
60 */
61 template<typename T>
62 inline size_t significant_bytes(T n)
63 {
64 for(size_t i = 0; i != sizeof(T); ++i)
65 if(get_byte(i, n))
66 return sizeof(T)-i;
67 return 0;
68 }
69
70 /**
71 * Compute Hamming weights
72 * @param n an integer value
73 * @return number of bits in n set to 1
74 */
75 template<typename T>
76 inline size_t hamming_weight(T n)
77 {
78 const byte NIBBLE_WEIGHTS[] = {
79 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
80
81 size_t weight = 0;
82 for(size_t i = 0; i != 2*sizeof(T); ++i)
83 weight += NIBBLE_WEIGHTS[(n >> (4*i)) & 0x0F];
84 return weight;
85 }
86
87 /**
88 * Count the trailing zero bits in n
89 * @param n an integer value
90 * @return maximum x st 2^x divides n
91 */
92 template<typename T>
93 inline size_t ctz(T n)
94 {
95 for(size_t i = 0; i != 8*sizeof(T); ++i)
96 if((n >> i) & 0x01)
97 return i;
98 return 8*sizeof(T);
99 }
100
101 }
102
103 #endif
Botan::ctz
size_t ctz(T n)
Definition: bit_ops.h:93
Botan::significant_bytes
size_t significant_bytes(T n)
Definition: bit_ops.h:62
Botan::get_byte
byte get_byte(size_t byte_num, T input)
Definition: get_byte.h:21
Botan::byte
unsigned char byte
Definition: types.h:22
Botan::high_bit
size_t high_bit(T n)
Definition: bit_ops.h:33
Botan
Definition: algo_base.h:14
Botan::power_of_2
bool power_of_2(T arg)
Definition: bit_ops.h:21
Botan::low_bit
size_t low_bit(T n)
Definition: bit_ops.h:48
Botan::hamming_weight
size_t hamming_weight(T n)
Definition: bit_ops.h:76