Converting an array of chars to std::string in order to pass into std::bitset seg fault

Viewed 560

before you down vote this please read carefully, it does get interesting. Basically I want to convert a type char array into an std::string in order to use std::bitset operations but when I try to create the bitset object at runtime I get this error.

terminate called after throwing an instance of 'std::invalid_argument' what(): bitset::_M_copy_from_ptr Aborted (core dumped)

Here's the code

#include <iostream>
#include <cstdlib>
#include <bitset>

int main()
{
    char BYTE_4[4] = { 1, 0, 0, 0};

    std::string str_BYTE_4 = std::string(BYTE_4);

    std::bitset<32> str_BYTE_4_bit( str_BYTE_4);//crash here
    std::cout<<"str_BYTE_4_bit. "<<str_BYTE_4_bit<<std::endl;

    return 0;
}

I also tried some other types of conversion with std::stringstream and pointers of both char and std::string and no matter what I pass into that std::bitset constructor I get the same error?

These are just snippets I commented out and removed from the above code, to show what I tried.

//char* BYTE_4 = new char[4];
    //std::stringstream SS;

    //std::string str_BYTE_4 = "0101";
    //SS << BYTE_4;
        //str_BYTE_4 = SS.str();
    //for(int index = 0; index < 4; index++)
        //    str_BYTE_4 += BYTE_4[index];

    //std::string *str_BYTE_4 = new std::string[4];
    //for( int index = 0; index < 4; index++)
        //    BYTE_4[index] = rand()%255;
2 Answers
Related