user968000
user968000

Reputation: 1843

string not outputting the data

I am reversing bits of an integer by first putting the bits in a string. Why cout of nu_string is an empty string.

    uint32_t reverseBits(uint32_t n) {
    string nu_bits;
    for(int i=0; i<32;i++){
        nu_bits.push_back(n>>i)&1);
        cout<<nu_bits<<endl; //prints nothing
    }
    //cout<<stoi(nu_bits); Throwing an exception
    //terminate called after throwing an instance of 'std::invalid_argument'
    //what():  stoi
    return n;
}

Upvotes: 0

Views: 57

Answers (2)

Waqar
Waqar

Reputation: 9386

Take a look at the ASCII table.

-----------------
Dec  |   CHAR VALUE
-----------------
0    |   NULL
1    |   SOH
...

Both of them are non printable characters. What you probably meant to add the the string was '0' and '1'. The values of which are 48 and 49 respectively.

So, change the push_back() to following

    nu_bits.push_back( ((n>>i) & 1) + '0' );
   //OR
    nu_bits.push_back( ((n>>i) & 1) + 48 );

Upvotes: 1

Brecht Sanders
Brecht Sanders

Reputation: 7315

push_back is for adding characters to a string, if the first character is 0 than the string is NUL-terminated and so will be empty. You probably meant to do this: nu_bits.push_back('0'+((n>>i)&1));

Upvotes: 1

Related Questions