Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
get_msb.hpp
Go to the documentation of this file.
1// === AUDIT STATUS ===
2// internal: { status: not started, auditors: [], date: YYYY-MM-DD }
3// external_1: { status: not started, auditors: [], date: YYYY-MM-DD }
4// external_2: { status: not started, auditors: [], date: YYYY-MM-DD }
5// =====================
6
7#pragma once
8#include <array>
9#include <cstddef>
10#include <cstdint>
11namespace bb::numeric {
12
13// from http://supertech.csail.mit.edu/papers/debruijn.pdf
14constexpr inline uint32_t get_msb32(const uint32_t in)
15{
16 constexpr std::array<uint8_t, 32> MultiplyDeBruijnBitPosition{ 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16,
17 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17,
18 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 };
19
20 uint32_t v = in | (in >> 1);
21 v |= v >> 2;
22 v |= v >> 4;
23 v |= v >> 8;
24 v |= v >> 16;
25
26 return MultiplyDeBruijnBitPosition[static_cast<uint32_t>(v * static_cast<uint32_t>(0x07C4ACDD)) >>
27 static_cast<uint32_t>(27)];
28}
29
30constexpr inline uint64_t get_msb64(const uint64_t in)
31{
32 constexpr std::array<uint8_t, 64> de_bruijn_sequence{ 0, 47, 1, 56, 48, 27, 2, 60, 57, 49, 41, 37, 28,
33 16, 3, 61, 54, 58, 35, 52, 50, 42, 21, 44, 38, 32,
34 29, 23, 17, 11, 4, 62, 46, 55, 26, 59, 40, 36, 15,
35 53, 34, 51, 20, 43, 31, 22, 10, 45, 25, 39, 14, 33,
36 19, 30, 9, 24, 13, 18, 8, 12, 7, 6, 5, 63 };
37
38 uint64_t t = in | (in >> 1);
39 t |= t >> 2;
40 t |= t >> 4;
41 t |= t >> 8;
42 t |= t >> 16;
43 t |= t >> 32;
44 return static_cast<uint64_t>(de_bruijn_sequence[(t * 0x03F79D71B4CB0A89ULL) >> 58ULL]);
45};
46
47template <typename T> constexpr inline T get_msb(const T in)
48{
49 return (sizeof(T) <= 4) ? get_msb32(in) : get_msb64(in);
50}
51
52template <typename T> constexpr inline T round_up_power_2(const T in)
53{
54 auto lower_bound = T(1) << get_msb(in);
55 return (lower_bound == in || lower_bound == 1) ? in : lower_bound * 2;
56}
57
58} // namespace bb::numeric
constexpr uint64_t get_msb64(const uint64_t in)
Definition get_msb.hpp:30
constexpr T get_msb(const T in)
Definition get_msb.hpp:47
constexpr T round_up_power_2(const T in)
Definition get_msb.hpp:52
constexpr uint32_t get_msb32(const uint32_t in)
Definition get_msb.hpp:14