I have a binary string that is potentially greater than 64 bits/characters. I would like to convert it into base-10 so that I can output it to the console.
As far as I know, c++ doesn't support any integers greater than 64 bits, with exceptions to compiler specific types. Therefore, I would need to convert the binary string to a base-10 string (as opposed to a base-10 integer) if I want to output it to the console in a human-readable form.
I have the following code...
int char_to_int(const char c) {
return ((int) c) - 48;
}
std::string string_addition(std::string s1, std::string s2) {
std::string ret = "";
// making sure the two strings are the same length
while(s1.size() > s2.size())
s2 = '0' + s2;
while (s2.size() > s1.size())
s1 = '0' + s1;
// adding and carrying
for (int32_t i = (int32_t) s1.size(); i >= 0; i--)
ret[i] = (char) ((char_to_int(s1[i]) + char_to_int(s2[i])) + 48);
for (int32_t i = (int32_t) ret.size() - 1; i >= 0; i--)
...
// then finally returning
return ret
}
std::string to_base_ten(const std::string& s) {
std::string ret = "";
for (size_t i = 0; i < s.size(); i++) {
// for each digit, calculate the appropriate number to add
int64_t temp = s[i] * (int) std::pow(2, i);
// performing addition with strings because of potential integer overflow issues
ret = string_addition(ret, std::to_string(temp));
}
return ret;
}
...which just gets tedious and hard to read/understand because of converting with strings. Are there any simpler or more efficient ways of accomplishing this task?
I will post this as an answer to the general query of "converting a binary string to a decimal string".
Assuming that the issue has to do with an arbitrary size decimal, then one solution is to use an arbitrary precision library. One such library is boost multiprecision, most notably the
boost::multiprecision::cpp_inttype.The following example shows usage of the
cpp_inttype, as well as thestd::accumulatefunction to build the decimal string, based on the current binary digit being processed:Output:
The
std::accumulatefunction will process the string from right-to-left (using the reverse iteratorsrbeginandrend), checking to see if the current digit is 1.If the digit is 1, then then value of 2^current_power is added to the total. The current power is incremented, and the process is repeated. The
str()function is a member ofcpp_intthat converts the final result to a string.Also note that there is no
string_additionfunction. It is not necessary when building thecpp_int, which will eventually be converted to a string at the end of the processing.