monotone

monotone Mtn Source Tree

Root/botan/bit_ops.cpp

1/*************************************************
2* Bit/Word Operations Source File *
3* (C) 1999-2008 The Botan Project *
4*************************************************/
5
6#include <botan/bit_ops.h>
7#include <botan/loadstor.h>
8
9namespace Botan {
10
11/*************************************************
12* Return true iff arg is 2**n for some n > 0 *
13*************************************************/
14bool power_of_2(u64bit arg)
15 {
16 if(arg == 0 || arg == 1)
17 return false;
18 if((arg & (arg-1)) == 0)
19 return true;
20 return false;
21 }
22
23/*************************************************
24* Return the index of the highest set bit *
25*************************************************/
26u32bit high_bit(u64bit n)
27 {
28 for(u32bit count = 64; count > 0; --count)
29 if((n >> (count - 1)) & 0x01)
30 return count;
31 return 0;
32 }
33
34/*************************************************
35* Return the index of the lowest set bit *
36*************************************************/
37u32bit low_bit(u64bit n)
38 {
39 for(u32bit count = 0; count != 64; ++count)
40 if((n >> count) & 0x01)
41 return (count + 1);
42 return 0;
43 }
44
45/*************************************************
46* Return the number of significant bytes in n *
47*************************************************/
48u32bit significant_bytes(u64bit n)
49 {
50 for(u32bit j = 0; j != 8; ++j)
51 if(get_byte(j, n))
52 return 8-j;
53 return 0;
54 }
55
56/*************************************************
57* Return the Hamming weight of n *
58*************************************************/
59u32bit hamming_weight(u64bit n)
60 {
61 u32bit weight = 0;
62 for(u32bit j = 0; j != 64; ++j)
63 if((n >> j) & 0x01)
64 ++weight;
65 return weight;
66 }
67
68}

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status