C++ - Decimal to binary converting

后端 未结 29 3638
一向
一向 2020-11-28 18:53

I wrote a \'simple\' (it took me 30 minutes) program that converts decimal number to binary. I am SURE that there\'s a lot simpler way so can you show me? Here\'s the code:<

29条回答
  •  醉酒成梦
    2020-11-28 19:54

    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 
    #include 
    
    int main()
    {
        std::string binary = std::bitset<8>(128).to_string(); //to binary
        std::cout<(binary).to_ulong();
        std::cout<

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

提交回复
热议问题