aboutsummaryrefslogtreecommitdiffstats
path: root/src/util.h
blob: f75c48ec303565832c838e575839060cb214d220 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#pragma once
#include <cstdint>
#include <vector>
#include <algorithm>
#include <cmath>

#include "config.h"
#include <cstring>

template<class T>
inline void SwapArray(T* p, const size_t len) {
    for (size_t i = 0, j = len - 1; i < len / 2; ++i, --j) {
        T tmp = p[i];
        p[i] = p[j];
        p[j] = tmp;
    }
}

template<size_t N>
inline void InvertSpectrInPlase(TFloat* in) {
    for (size_t i = 0; i < N; i+=2)
        in[i] *= -1;
}

template<size_t N>
inline std::vector<TFloat> InvertSpectr(const TFloat* in) {
    std::vector<TFloat> buf(N);
    std::memcpy(&buf[0], in, N * sizeof(TFloat));
    InvertSpectrInPlase<N>(&buf[0]);
    return buf;
}

inline uint16_t GetFirstSetBit(uint32_t x) {
    static const uint16_t multiplyDeBruijnBitPosition[32] = {
        0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
        8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
    };
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    return multiplyDeBruijnBitPosition[(uint32_t)(x * 0x07C4ACDDU) >> 27];
}

template<class T>
inline uint16_t Log2FloatToIdx(T x, uint16_t shift) {
    T t = x * shift;
    return GetFirstSetBit(std::trunc(t));
}

template<class T>
inline T CalcMedian(T* in, uint32_t len) {
    std::vector<T> tmp(in, in+len);
    std::sort(tmp.begin(), tmp.end());
    uint32_t pos = (len - 1) / 2;
    return tmp[pos];
}