void convertBinaryToDecimal(std::string BinarySrc, std::string& DecimalDest)
{
}
I need to convert a string binary length 128 bit to string Decimal
void convertBinaryToDecimal(std::string BinarySrc, std::string& DecimalDest)
{
}
I need to convert a string binary length 128 bit to string Decimal
The algorithm is simple:
v
initialized to 0
;BinarySrc
, v = v + v + bit
;digit = '0' + v % 10
while (v /= 10) != 0
.This should be easy to convert to code.
For the answer given by user chqrlie, I would immediately ask, where we have nowadays 128 bit unsigned integer variables, and even if so, what will we do with 500 bit strings? So, this approach will of course not work.
What we need here, is an integer division for binary numbers. Then, we will do the same as we would do for decimals. Make an integer division by 10, and the remainder is the digit that we are interested in.
The below shown functionality works for arbitrary long strings with binary numbers. Also with other number bases
Please see:
EDIT
Updated according to the very good observation by user chux
#include <iostream>
#include <string>
#include <algorithm>
int main() {
// This is the input number
std::string binAsString{ "101010" };
// Show orignial string to user
std::cout << "\n\n" << binAsString;
// Here we will store the resulting output
std::string result{};
// The conversion will also work for other number bases
// For base > 10 you need to adapt the creation of the digit at the bottom
constexpr unsigned int numberBase{ 10 };
// So, we will perfrom an integer division by 10, until the number is 0
do {
// The remainder is the digit that we are interested in
unsigned int remainder{};
// Temporary result of integer division
std::string dividedNumberAsString{};
// Do the division
for (const char bit : binAsString) {
// Calculate the remainder
remainder = remainder * 2 + (bit - '0');
// If we have a overflow (e.g. number is bigger than 10)
if (remainder >= numberBase) {
// Handle overflow
remainder -= numberBase;
// Add character 1 to the "devidedString"
dividedNumberAsString += "1";
}
else {
dividedNumberAsString += "0";
}
}
// Now "dividedNumberAsString" as string is the result of the devision by e.g. 10 in binary form
binAsString = dividedNumberAsString;
// The remainder is the number that we are interested in
result.insert(0, 1, '0' + remainder);
// Continue the loop with the new binary string
} while (std::count(binAsString.begin(), binAsString.end(), '1'));
// Show result
std::cout << " -->\n" << result << "\n\n";
return 0;
}
Rather than providing solution directly I think I can give you a small hint.
Take the long binary number, and split it in half (or quarters, or whatever.)
Keep track of which of these is the upper range and which of these is the lower range of the binary number.
Calculate what the true value of lower range and upper range and add them together afterwards.