C++ Online Compiler
Example: Binary to Decimal using Manual Shift in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Binary to Decimal using Manual Shift #include <iostream> int main() { long long binaryNumber; std::cout << "Enter a binary number: "; std::cin >> binaryNumber; long long decimalNumber = 0; long long base = 1; // Represents 2^0, 2^1, 2^2, ... int remainder; // Step 1: Loop while the binary number is not zero while (binaryNumber != 0) { // Step 2: Get the last digit remainder = binaryNumber % 10; // Step 3: Remove the last digit binaryNumber /= 10; // Step 4: Add (remainder * current base value) to decimalNumber decimalNumber += remainder * base; // Step 5: Double the base for the next power of 2 base *= 2; } std::cout << "Decimal equivalent: " << decimalNumber << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS