C++ Online Compiler
Example: Binary to Decimal using std::bitset in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Binary to Decimal using std::bitset #include <iostream> #include <string> // Required for std::string #include <bitset> // Required for std::bitset int main() { std::string binaryString; std::cout << "Enter a binary string: "; std::cin >> binaryString; // Step 1: Create a bitset from the binary string // The template parameter specifies the maximum number of bits // Ensure it's large enough for your expected binary numbers. // For example, 64 bits for unsigned long long. try { std::bitset<64> bits(binaryString); // Max 64 bits // Step 2: Convert the bitset to an unsigned long long unsigned long long decimalNumber = bits.to_ullong(); std::cout << "Decimal equivalent: " << decimalNumber << std::endl; } catch (const std::invalid_argument& e) { std::cerr << "Error: Invalid binary string entered. " << e.what() << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS