C++ Online Compiler
Example: Binary to Base 9 Conversion in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Binary to Base 9 Conversion #include <iostream> #include <cmath> // Required for pow function #include <string> // Required for string manipulation if we build base 9 as a string #include <algorithm> // Required for std::reverse // Function to convert a binary number to its decimal equivalent long long binaryToDecimal(long long binaryNum) { long long decimalNum = 0; long long base = 1; // Represents powers of 2 (2^0, 2^1, 2^2, ...) while (binaryNum > 0) { int lastDigit = binaryNum % 10; // Get the last digit of the binary number binaryNum /= 10; // Remove the last digit from the binary number decimalNum += lastDigit * base; // Add the product of digit and base (power of 2) base *= 2; // Move to the next power of 2 } return decimalNum; } // Function to convert a decimal number to its base 9 equivalent // Returns the base 9 number as a long long (e.g., 30 for 27 decimal) long long decimalToBase9(long long decimalNum) { if (decimalNum == 0) return 0; std::string base9Str = ""; // To build the base 9 representation while (decimalNum > 0) { int remainder = decimalNum % 9; // Get the remainder when divided by 9 base9Str += std::to_string(remainder); // Convert remainder to char and append decimalNum /= 9; // Divide decimal number by 9 } std::reverse(base9Str.begin(), base9Str.end()); // Reverse the string to get correct order return std::stoll(base9Str); // Convert the string back to a long long } int main() { // Step 1: Declare variables for binary input long long binaryInput; // Step 2: Prompt user for binary number std::cout << "Enter a binary number: "; std::cin >> binaryInput; // Step 3: Convert binary to decimal long long decimalResult = binaryToDecimal(binaryInput); std::cout << "Decimal equivalent: " << decimalResult << std::endl; // Step 4: Convert decimal to base 9 long long base9Result = decimalToBase9(decimalResult); std::cout << "Base 9 equivalent: " << base9Result << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS