General: standard compliance with underscores
[marnav.git] / include / marnav / utils / bitset_string.hpp
blob1e85c9e1c9b9232601d5f8cbf5819a20faa1ba1b
1 #ifndef MARNAV_UTILS_BITSET_STRING_HPP
2 #define MARNAV_UTILS_BITSET_STRING_HPP
4 /// Copyright (c) 2016 Mario Konrad <mario.konrad@gmx.net>
5 /// The code is licensed under the BSD License.
7 #include "bitset.hpp"
8 #include <string>
10 namespace marnav
12 namespace utils
14 /// Renders the bitset as string.
15 ///
16 /// @param[in] bits The bits to render.
17 /// @return String representing the bitset as continous stream of '0' and '1'.
18 template <class T> std::string to_string(const bitset<T> & bits)
20 std::string result;
21 result.reserve(bits.size());
22 for (auto const & b : bits)
23 result += '0' + b;
24 return result;
27 /// Renders the bitset as string, packed by specified number of bits.
28 ///
29 /// @param[in] bits The bits to render.
30 /// @param[in] pack Number of bits per pack.
31 /// @param[in] delm Delimitter to separate the packs.
32 /// @return String representing the bitset as stream of '0' and '1', separated by
33 /// the delimitter.
34 template <class T>
35 std::string to_string(const bitset<T> & bits, std::size_t pack, char delm = ' ')
37 if ((pack == 0) || (pack >= bits.size()))
38 return to_string(bits);
40 std::string result;
42 // reserve space, wasted space at most: sizeof(delm) characters
43 result.reserve(bits.size() + sizeof(delm) * (bits.size() / pack));
45 std::size_t i = 1;
46 auto begin = bits.begin();
47 for (;;) {
48 result += '0' + *begin;
49 ++begin;
50 if (begin == bits.end())
51 break;
52 if (i == pack) {
53 result += delm;
54 i = 0;
56 ++i;
59 return result;
64 #endif