monotone

monotone Mtn Source Tree

Root/botan/bit_ops.cpp

1/*************************************************
2* Bit/Word Operations Source File *
3* (C) 1999-2006 The Botan Project *
4*************************************************/
5
6#include <botan/bit_ops.h>
7
8namespace Botan {
9
10/*************************************************
11* XOR arrays together *
12*************************************************/
13void xor_buf(byte data[], const byte mask[], u32bit length)
14 {
15 while(length >= 8)
16 {
17 data[0] ^= mask[0]; data[1] ^= mask[1];
18 data[2] ^= mask[2]; data[3] ^= mask[3];
19 data[4] ^= mask[4]; data[5] ^= mask[5];
20 data[6] ^= mask[6]; data[7] ^= mask[7];
21 data += 8; mask += 8; length -= 8;
22 }
23 for(u32bit j = 0; j != length; ++j)
24 data[j] ^= mask[j];
25 }
26
27void xor_buf(byte out[], const byte in[], const byte mask[], u32bit length)
28 {
29 while(length >= 8)
30 {
31 out[0] = in[0] ^ mask[0]; out[1] = in[1] ^ mask[1];
32 out[2] = in[2] ^ mask[2]; out[3] = in[3] ^ mask[3];
33 out[4] = in[4] ^ mask[4]; out[5] = in[5] ^ mask[5];
34 out[6] = in[6] ^ mask[6]; out[7] = in[7] ^ mask[7];
35 in += 8; out += 8; mask += 8; length -= 8;
36 }
37 for(u32bit j = 0; j != length; ++j)
38 out[j] = in[j] ^ mask[j];
39 }
40
41/*************************************************
42* Return true iff arg is 2**n for some n > 0 *
43*************************************************/
44bool power_of_2(u64bit arg)
45 {
46 if(arg == 0 || arg == 1)
47 return false;
48 if((arg & (arg-1)) == 0)
49 return true;
50 return false;
51 }
52
53/*************************************************
54* Return the index of the highest set bit *
55*************************************************/
56u32bit high_bit(u64bit n)
57 {
58 for(u32bit count = 64; count > 0; --count)
59 if((n >> (count - 1)) & 0x01)
60 return count;
61 return 0;
62 }
63
64/*************************************************
65* Return the index of the lowest set bit *
66*************************************************/
67u32bit low_bit(u64bit n)
68 {
69 for(u32bit count = 0; count != 64; ++count)
70 if((n >> count) & 0x01)
71 return (count + 1);
72 return 0;
73 }
74
75/*************************************************
76* Return the number of significant bytes in n *
77*************************************************/
78u32bit significant_bytes(u64bit n)
79 {
80 for(u32bit j = 0; j != 8; ++j)
81 if(get_byte(j, n))
82 return 8-j;
83 return 0;
84 }
85
86/*************************************************
87* Return the Hamming weight of n *
88*************************************************/
89u32bit hamming_weight(u64bit n)
90 {
91 u32bit weight = 0;
92 for(u32bit j = 0; j != 64; ++j)
93 if((n >> j) & 0x01)
94 ++weight;
95 return weight;
96 }
97
98}

Archive Download this file

Branches

Tags

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