arduino-audio-tools
Loading...
Searching...
No Matches
BitVector.h
Go to the documentation of this file.
1#pragma once
2#ifdef HAS_IOSTRAM
3#include "Vector.h"
4#include <stdint.h>
5#include <iostream>
6
7namespace audio_tools {
8
15class BitVector {
16public:
17 BitVector() = default;
18 BitVector(int size) {
19 resize(size);
20 }
21
22 inline bool operator[](size_t index) { return get(index); }
23
24 bool get(int64_t index) {
25 if (index < 0)
26 return false;
27 bool result = false;
28 int offset = index / sizeof(uint64_t);
29 int bit = index % sizeof(uint64_t);
30 if (offset < vector.size()) {
31 uint64_t value = vector[offset];
32 // get bit
33 result = (value >> bit) & 1U;
34 }
35 return result;
36 }
37
38 void set(int64_t index, bool value) {
39 if (index < 0)
40 return;
41 max_idx = max(max_idx, index + 1);
42 int offset = index / sizeof(uint64_t);
43 int bit = index % sizeof(uint64_t);
44 while (offset >= vector.size()) {
45 vector.push_back(0l);
46 }
47 // check if we need to updte the value
48 if (((vector[offset] >> bit) & 1U) != value) {
49 // needs update
50 if (value) {
51 // set bit
52 vector[offset] |= 1UL << bit;
53 } else {
54 // clear bit
55 vector[offset] &= ~(1UL << bit);
56 }
57 // call change handler to notify about change
58 if (changeHandler != nullptr) {
59 changeHandler(index, value, ref);
60 }
61 }
62 }
63
64 void clear() {
65 max_idx = 0;
66 vector.clear();
67 vector.shrink_to_fit();
68 }
69
70 int size() { return max_idx; }
71
73 void setChangeCallback(void (*hdler)(int idx, bool value, void *ref),
74 void *ref = nullptr) {
76 this->ref = ref;
77 }
78
80 bool resize(size_t size) {
81 max_idx = size;
82 int round_up = size % 64 != 0;
83 if (!vector.resize(size / 64 + round_up)) {
84 return false;
85 }
86 for (int j=0;j<max_idx;j++){
87 set(j, 0);
88 }
89 return true;
90 }
91
92 // shifts n bits: + to the right; - to the left
93 void shift(int n) {
94 if (n == 0)
95 return;
96 for (int j = 0; j < max_idx - n; j++) {
97 set(j, get(j - n));
98 }
99 max_idx+=n;
100 }
102 template <typename T> T toInt(int n) {
103 T result;
104 for (int j = 0; j < sizeof(T) * 8; j++) {
105 bool x = get(n);
106 // set bit at pos
107 result ^= (-x ^ result) & (1UL << j);
108 }
109 return result;
110 }
111
112
113protected:
114 Vector<uint64_t> vector;
115 void (*changeHandler)(int idx, bool value, void *ref) = nullptr;
116 void *ref;
117 int64_t max_idx = 0;
118};
119
120
121} // namespace audio_tools
122
123#endif
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition AudioCodecsBase.h:10
size_t writeData(Print *p_out, T *data, int samples, int maxSamples=512)
Definition AudioTypes.h:508