how to transform a Decimal integer to a binary using function

Write your question here.
Using function ,and cin a positive decimal integer,cout a binary.c++ please.
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <bitset>
int main()
{
    int x;
    std::cin >> x;
    std::bitset<8> bits(x);
    std::cout << bits;
}  


Now you turn it into a function and handle making sure the bitset is large enough; the size of bitset is fixed at compile time, so you might not like this method.

If you make the bitset 64 bits long, it will cover any input int you could type (assuming you're using a conventional PC). You could then turn it into a string (using the bitset class function to_string ) and then remove the leading zeroes to make it look pretty.
Last edited on
Topic archived. No new replies allowed.