From f932df32535a85c934d632c17a2dfdf8c495cdc5 Mon Sep 17 00:00:00 2001 From: dm1sh Date: Sat, 11 Dec 2021 20:37:46 +0300 Subject: [PATCH] Added convertation to string to BitArray --- QRCodeLibrary/BitArray.cpp | 15 ++++++++++++++- QRCodeLibrary/BitArray.hpp | 5 ++++- tests/BitArray_test.cpp | 4 ++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/QRCodeLibrary/BitArray.cpp b/QRCodeLibrary/BitArray.cpp index 35f9bce..476a654 100644 --- a/QRCodeLibrary/BitArray.cpp +++ b/QRCodeLibrary/BitArray.cpp @@ -1,11 +1,24 @@ #include "pch.h" + +#include + #include "BitArray.hpp" -bool BitArray::get(unsigned index) +bool BitArray::get(unsigned index) const { 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((*this).get(i)); + + return res.str(); +} + void BitArray::set(unsigned index, bool val) { if (val) diff --git a/QRCodeLibrary/BitArray.hpp b/QRCodeLibrary/BitArray.hpp index 5a45ec1..63d43e9 100644 --- a/QRCodeLibrary/BitArray.hpp +++ b/QRCodeLibrary/BitArray.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include using namespace std; @@ -12,11 +13,13 @@ class BitArray { public: BitArray(unsigned size_ = 0) : size{ size_ }, v(ceil_div(size_, 8)) {}; + + operator std::string() const; unsigned size; vector v; - bool get(unsigned index); + bool get(unsigned index) const; void set(unsigned index, bool val); unsigned set(unsigned index, int32_t val, unsigned size); }; diff --git a/tests/BitArray_test.cpp b/tests/BitArray_test.cpp index 2ee35d3..98c5063 100644 --- a/tests/BitArray_test.cpp +++ b/tests/BitArray_test.cpp @@ -24,6 +24,10 @@ TEST_F(BitArrayTests, GetsBitByIndex) { EXPECT_EQ(a1.get(1), 0); } +TEST_F(BitArrayTests, Converts_to_string) { + EXPECT_EQ(std::string(a1), "101010101111111"); +} + TEST_F(BitArrayTests, SetsIndividualBit) { a1.set(0, 0); a1.set(1, 1);