Added convertation to string to BitArray

This commit is contained in:
Dmitriy Shishkov 2021-12-11 20:37:46 +03:00
parent 105887d468
commit f932df3253
3 changed files with 22 additions and 2 deletions

View File

@ -1,11 +1,24 @@
#include "pch.h" #include "pch.h"
#include <sstream>
#include "BitArray.hpp" #include "BitArray.hpp"
bool BitArray::get(unsigned index) bool BitArray::get(unsigned index) const
{ {
return (v[index / 8] >> (8 - 1 - index % 8)) & 1; return (v[index / 8] >> (8 - 1 - index % 8)) & 1;
} }
BitArray::operator std::string() const
{
std::stringstream res;
for (unsigned i = 0; i < size; i++)
res << static_cast<int>((*this).get(i));
return res.str();
}
void BitArray::set(unsigned index, bool val) void BitArray::set(unsigned index, bool val)
{ {
if (val) if (val)

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <vector> #include <vector>
#include <string>
using namespace std; using namespace std;
@ -12,11 +13,13 @@ class BitArray
{ {
public: public:
BitArray(unsigned size_ = 0) : size{ size_ }, v(ceil_div(size_, 8)) {}; BitArray(unsigned size_ = 0) : size{ size_ }, v(ceil_div(size_, 8)) {};
operator std::string() const;
unsigned size; unsigned size;
vector<unsigned char> v; vector<unsigned char> v;
bool get(unsigned index); bool get(unsigned index) const;
void set(unsigned index, bool val); void set(unsigned index, bool val);
unsigned set(unsigned index, int32_t val, unsigned size); unsigned set(unsigned index, int32_t val, unsigned size);
}; };

View File

@ -24,6 +24,10 @@ TEST_F(BitArrayTests, GetsBitByIndex) {
EXPECT_EQ(a1.get(1), 0); EXPECT_EQ(a1.get(1), 0);
} }
TEST_F(BitArrayTests, Converts_to_string) {
EXPECT_EQ(std::string(a1), "101010101111111");
}
TEST_F(BitArrayTests, SetsIndividualBit) { TEST_F(BitArrayTests, SetsIndividualBit) {
a1.set(0, 0); a1.set(0, 0);
a1.set(1, 1); a1.set(1, 1);