How to erase the extra leading zeros from bitset?

I've written the following program-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<bits/stdc++.h>

using namespace std;

int main()
{
    unsigned int num;
    cin>>num;

    cout<<bitset<32>(num)<<endl;

    return 0;
}


When I give 21 as input it prints 00000000000000000000000000010101

But I want to print only 10101. How to do that?
Convert bitset to string and trim leading zeroes.
The header is <bitset>; <bits/stdc++.h> is not a standard header.

std::numeric_limits< unsigned int >::digits gives the number of bits in an unsigned int
http://en.cppreference.com/w/cpp/types/numeric_limits/digits

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <bitset>  // **** <bits/stdc++.h> is not a standard header
#include <limits>
#include <string>

int main()
{
    // numbr of bnary digits in unsigned int
    // http://en.cppreference.com/w/cpp/types/numeric_limits/digits
    const std::size_t NBITS = std::numeric_limits< unsigned int >::digits ;

    unsigned int n ;
    std::cin >> n ;
    
    std::cout << "decimal: " << n << "  binary: " ;
    const std::bitset<NBITS> bits(n) ;

    const std::string str_bits = bits.to_string() ; // convert to a string of zeroes and ones
    
    // http://en.cppreference.com/w/cpp/string/basic_string/find
    const auto first_digit = str_bits.find('1') ; // locate the first '1'

    if( first_digit != std::string::npos ) // found it; print the substring starting at the first '1'
        std::cout << str_bits.substr(first_digit) << '\n' ; 
        // http://en.cppreference.com/w/cpp/string/basic_string/substr
        
    else std::cout << "0\n" ; // all the bits were zeroes
}

http://coliru.stacked-crooked.com/a/1f9e4f49c908b577
Topic archived. No new replies allowed.