comparison BitArray.hpp @ 52:725b0d776f3c

Fix a lot of problems with BitArray and reorganize which functions are located in header and file.
author Tom Fredrik Blenning Klaussen <bfg@blenning.no>
date Thu, 13 Sep 2012 23:23:14 +0200
parents b23f04d4a276
children f339499ecd79
comparison
equal deleted inserted replaced
51:0bd3c1c46251 52:725b0d776f3c
4 4
5 #if 0 5 #if 0
6 #include <QtCore/QBitArray> 6 #include <QtCore/QBitArray>
7 typedef QBitArray BitArray; 7 typedef QBitArray BitArray;
8 #else 8 #else
9 #include <ostream>
10
9 #define HIGH(B) ((B) >> 3) 11 #define HIGH(B) ((B) >> 3)
10 #define LOW(B) ((B) & 0x07) 12 #define LOW(B) ((B) & 0x07)
11 13
12 #define MASK(X) (0x1 << X) 14 #define MASK(X) (0x1 << (7 - X))
13 #define SELECTMASK(X) (uchar(MASK(X))) 15 #define SELECTMASK(X) (uchar(MASK(X)))
14 #define DESELECTMASK(X) (uchar(~MASK(X))) 16 #define DESELECTMASK(X) (uchar(~MASK(X)))
15 17
16 #define NUMCHARS(X) HIGH(X + 7) 18 #define NUMCHARS(X) HIGH(X + 7)
17 19
22 { 24 {
23 typedef unsigned char uchar; 25 typedef unsigned char uchar;
24 typedef unsigned int uint; 26 typedef unsigned int uint;
25 uint size_; 27 uint size_;
26 unsigned char* bits; 28 unsigned char* bits;
29
27 public: 30 public:
31 BitArray(uint size, bool val) : size_(size), bits(new uchar[NUMCHARS(size)])
32 {
33 uint n = NUMCHARS(size);
34 for (uint i = 0; i < n; ++i) {
35 bits[i] = (val) ? 0xff : 0;
36 }
37 }
38
39 BitArray(uint size) : size_(size), bits(new uchar[NUMCHARS(size)])
40 {
41 bits[NUMCHARS(size) - 1] = 0;
42 }
43
44 BitArray() : size_(0), bits(0)
45 {
46 }
47
48 BitArray(const BitArray& );
49
50 ~BitArray();
28 bool testBit(uint i) const 51 bool testBit(uint i) const
29 { 52 {
30 assert(i < size_); 53 assert(i < size_);
31 return bits[HIGH(i)] & MASK(LOW(i)); 54 return bits[HIGH(i)] & MASK(LOW(i));
32 } 55 }
40 else { 63 else {
41 bits[HIGH(i)] &= DESELECTMASK(LOW(i)); 64 bits[HIGH(i)] &= DESELECTMASK(LOW(i));
42 } 65 }
43 } 66 }
44 67
45 BitArray(uint size)
46 {
47 size_ = size;
48 bits = new uchar[NUMCHARS(size)];
49 }
50
51 BitArray(uint size, bool val) : size_(size), bits(new uchar[NUMCHARS(size)])
52 {
53 uint n = NUMCHARS(size);
54 for (uint i = 0; i < n; ++i) {
55 bits[i] = (val) ? 0xff : 0;
56 }
57 }
58
59 BitArray() : size_(0), bits(0)
60 {
61 }
62
63 uint size() const 68 uint size() const
64 { 69 {
65 return size_; 70 return size_;
66 } 71 }
72
73 uchar getPaddedChar(size_t offset = 0) const
74 {
75 assert(size_ > 0);
76 assert(HIGH(offset) < NUMCHARS(size_));
77 if (LOW(offset) == 0)
78 return bits[HIGH(offset)];
79
80 uchar next = ((HIGH(offset) + 1) < NUMCHARS(size_)) ?
81 bits[HIGH(offset) + 1] : 0;
82 return ((bits[HIGH(offset)] << 8) | next) >> (8 - LOW(offset));
83 }
84
85
86 bool operator==(const BitArray& rhs) const;
87 BitArray& operator=(const BitArray& rhs);
67 }; 88 };
89
90 std::ostream& operator<<(std::ostream& out, const BitArray& rhs);
91
68 #endif 92 #endif
69 93
70 #endif //BITARRAY_HPP 94 #endif //BITARRAY_HPP
71
72