C++ – Decimal to binary converting

std::bitset has a .to_string() method that returns a std::string holding a text representation in binary, with leading-zero padding.

Choose the width of the bitset as needed for your data, e.g. std::bitset<32> to get 32-character strings from 32-bit integers.

#include <iostream>
#include <bitset>

int main()
{
    std::string binary = std::bitset<8>(128).to_string(); //to binary
    std::cout<<binary<<"\n";

    unsigned long decimal = std::bitset<8>(binary).to_ulong();
    std::cout<<decimal<<"\n";
    return 0;
}

EDIT: Please do not edit my answer for Octal and Hexadecimal. The OP specifically asked for Decimal To Binary.

Leave a Comment