C++ Online Compiler
Example: Binary to Septenary Converter in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Binary to Septenary Converter #include <iostream> #include <string> #include <algorithm> // Required for std::reverse // Function to convert binary to decimal long long binaryToDecimal(long long binaryNumber) { long long decimalNumber = 0; long long base = 1; // Represents powers of 2 (2^0, 2^1, 2^2, ...) while (binaryNumber > 0) { int lastDigit = binaryNumber % 10; // Get the last digit (either 0 or 1) binaryNumber = binaryNumber / 10; // Remove the last digit decimalNumber += lastDigit * base; // Add the product of digit and power of 2 base *= 2; // Move to the next power of 2 } return decimalNumber; } // Function to convert decimal to septenary long long decimalToSeptenary(long long decimalNumber) { if (decimalNumber == 0) { return 0; // Special case for input 0 } std::string septenaryString = ""; while (decimalNumber > 0) { int remainder = decimalNumber % 7; // Get the remainder when divided by 7 septenaryString += std::to_string(remainder); // Append remainder to string decimalNumber /= 7; // Update decimal number } std::reverse(septenaryString.begin(), septenaryString.end()); // Reverse the string return std::stoll(septenaryString); // Convert string back to long long } int main() { // Step 1: Declare a variable to store the binary input long long binaryInput; // Step 2: Prompt the user to enter a binary number std::cout << "Enter a binary number: "; std::cin >> binaryInput; // Step 3: Convert the binary number to its decimal equivalent long long decimalValue = binaryToDecimal(binaryInput); // Step 4: Convert the decimal value to its septenary equivalent long long septenaryValue = decimalToSeptenary(decimalValue); // Step 5: Display the result std::cout << "Binary " << binaryInput << " = Septenary " << septenaryValue << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS