Theoretica
A C++ numerical and automatic mathematical library
bit_op.h
Go to the documentation of this file.
1 
5 
6 #ifndef THEORETICA_BIT_OP_H
7 #define THEORETICA_BIT_OP_H
8 
9 #include <cstdint>
10 
11 
12 namespace theoretica {
13 
14 
24  inline void mul_uint128(
25  uint64_t a, uint64_t b,
26  uint64_t& c_low, uint64_t& c_high) {
27 
28  // Lowest and highest 32 bits of a and b
29  const uint64_t a_low = a & 0xffffffff;
30  const uint64_t a_high = a >> 32;
31 
32  const uint64_t b_low = b & 0xffffffff;
33  const uint64_t b_high = b >> 32;
34 
35  uint64_t m[4];
36 
37  // Multiplication terms for (a_l + a_h) * (b_l + b_h)
38  m[0] = a_low * b_low;
39  m[1] = a_low * b_high;
40  m[2] = a_high * b_low;
41  m[3] = a_high * b_high;
42 
43  // Multiplication carry for c_high
44  uint64_t carry = (
45  (m[0] >> 32) +
46  (m[1] & 0xffffffff) +
47  (m[2] & 0xffffffff)) >> 32;
48 
49  c_low = m[0] + (m[1] << 32) + (m[2] << 32);
50  c_high = m[3] + (m[1] >> 32) + (m[2] >> 32) + carry;
51  }
52 
53 
62  inline uint64_t mix_mum(uint64_t a, uint64_t b) {
63 
64  uint64_t c_low, c_high;
65  mul_uint128(a, b, c_low, c_high);
66 
67  return c_high ^ c_low;
68  }
69 
70 
76  template<typename UnsignedIntType>
77  inline TH_CONSTEXPR UnsignedIntType
78  bit_rotate(UnsignedIntType x, unsigned int i) {
79 
80  return (x << i) | (x >> ((sizeof(UnsignedIntType) * 8) - i));
81  }
82 
83 
89  template<typename Vector, enable_vector<Vector> = true>
90  inline void swap_bit_reverse(Vector& x, unsigned int m) {
91 
92  if (x.size() < (uint64_t(1) << m)) {
93  TH_MATH_ERROR("swap_bit_reverse", x.size(), INVALID_ARGUMENT);
94  return;
95  }
96 
97  for (unsigned int i = 0; i < x.size(); i++) {
98 
99  unsigned int j = 0;
100 
101  for (unsigned int k = 0; k < m; k++)
102  j = (j << 1) | ((i >> k) & 0x01);
103 
104  if (j > i)
105  std::swap(x[i], x[j]);
106  }
107  }
108 }
109 
110 
111 #endif
#define TH_CONSTEXPR
Enable constexpr in function declarations if C++14 is supported.
Definition: constants.h:151
#define TH_MATH_ERROR(F_NAME, VALUE, EXCEPTION)
TH_MATH_ERROR is a macro which throws exceptions or modifies errno (depending on which compiling opti...
Definition: error.h:219
Main namespace of the library which contains all functions and objects.
Definition: algebra.h:27
TH_CONSTEXPR UnsignedIntType bit_rotate(UnsignedIntType x, unsigned int i)
Bit rotation of unsigned integer types using shifts.
Definition: bit_op.h:78
uint64_t mix_mum(uint64_t a, uint64_t b)
MUM bit mixing function, computes the 128-bit product of a and b and the XOR of their high and low 64...
Definition: bit_op.h:62
void mul_uint128(uint64_t a, uint64_t b, uint64_t &c_low, uint64_t &c_high)
Multiply two 64-bit unsigned integers and store the result in two 64-bit variables,...
Definition: bit_op.h:24
void swap_bit_reverse(Vector &x, unsigned int m)
Swap the elements of a vector pair-wise, by exchanging elements with indices related by bit reversion...
Definition: bit_op.h:90