Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary string to integer string c++ [duplicate]

Possible Duplicate:
Converting string of 1s and 0s into binary value

I would like to convert a binary string to an integer string in c++. e.g:

"000000000010" becomes "2"

I have the following constraint: i can not convert this string to an integer type and then convert it again to string because that binary string can be very huge!

I already tried to do it with stringstream, inserting the binary string to it with the flag std::stringstream::binary and then output the content using the std::dec flag, but it doesn't work

Thank you all in advance.

like image 609
jav974 Avatar asked May 09 '26 18:05

jav974


2 Answers

You can construct a std::bitset from a std::string, and use std::bitset::to_ulong or std::bitset::to_ullong to get an integer. Be sure to take care of endianness, it is not done for you.

If you need a string from the integer, use std::to_string.

like image 165
rubenvb Avatar answered May 12 '26 07:05

rubenvb


You could go about it like this:

  • create a new output string, containing "0"
  • for each character of the (reversed) original string:
    • multiply the result by 2 (digit by digit, taking care of the carry)
    • if the digit is a '1', add 1 to the result (as above)
  • reverse the result (use std::reverse)
like image 27
Grzegorz Herman Avatar answered May 12 '26 08:05

Grzegorz Herman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!