-1

I need to save some data and the only viable option is a std::string; so I get a bool array passed as a void*. Now I need to save it in a way that I can convert it into a std::string and be able read a void* to a bool[] from that exact string. Sadly I got lost in conversion.

f(const void* data, int length){

   bool** boolPointer = (bool**)(data);
   bool boolArray[length];

   for (int i=0; i<=length; i++){
       boolArray[i] = p[sizeof(bool)*i];
   }

   std::string s = (std::string&)boolArray;
}

I'm pretty sure the last line is no viable conversion, but that was my attempt.

Thilo
  • 8,827
  • 2
  • 35
  • 56
dos
  • 135
  • 1
  • 6

3 Answers3

3

Does this work for you?

char f(bool b)
{
    return b ? '1' : '0';
}

int main()
{
    // let's just consider whatever is there in this uninitialized array
    bool buf[100];

    std::string s;

    // transform and copy (convert true to '1' and false to '0')
    std::transform(&buf[0], &buf[99], std::back_inserter(s), f);

    std::cout << s << std::endl;
}

If you are on C++11, you can use the following code snippet

int main()
{
    bool buf[100];

    std::string s;

    std::transform(&buf[0], &buf[99], std::back_inserter(s), [](bool const &b){ return b ? '1' : '0'; });
    std::cout << s << std::endl;
}
Chubsdad
  • 24,777
  • 4
  • 73
  • 129
0

Well, I guess you could just open up your C++ book...

std::string f(std::vector<unsigned char> const& v)
{
    std::string temp;

    for (auto c : v) {
        for (unsigned i = 0; i < 8; ++i) {
            temp += (c & (1 << i)) ? '1' : '0';
        }
    }

    return temp;
}

That could probably be done even easier with something like std::copy or some other cryptic back_inserter thingy, but I wanted to keep it simple. Another option would be to use std::bitset or your own encapsulation, to get rid of ugly bit operations.

If you're forced by the devil to pass the data by void*, just convert it to vector:

unsigned char* begin = static_cast<unsigned char*>(data);
vector<unsigned char> v (begin, begin + length);

Please also note that if it's for serialization purposes, that representation will be hardly readable both by computer and a human. If it's meant to be read by computer, save it as binary without conversions. If it's meant to be read by humans, save it as hex characters (splitting every byte in half).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
0

You can overload the output operator to convert the booleans to whatever you want:

ostream& operator<<(const ostream& os, const bool& value) {
    return os << (value ? "1" : "0");
}

Then copy the array to a stringstream:

int main() {
    // ...
    ostringstream oss;
    copy(data, data+size, ostream_iterator<bool>(oss));

    oss.str(); // this is the string you're looking for
    // ...
}
Peter Wood
  • 23,859
  • 5
  • 60
  • 99