How to find position of bit set in a binary number??

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
29
30
31
32
33
34
#include <iostream>
#include <limits>

void doBinaryJunk(unsigned n)
{
    unsigned mask = 1 << (std::numeric_limits<unsigned>::digits-1) ;
    
    unsigned count[2] = {0}; 

    // skip leading 0's:
    while ( mask && !(mask & n) )
        mask >>= 1 ;

    while ( mask )
    {
        unsigned digit = (mask & n) != 0 ;
        ++count[digit] ;

        std::cout << digit;
        mask >>= 1 ;
    }

    std::cout << "\n\t0: " << count[0] << "\n\t1: " << count[1] << '\n' ;
}


int main()
{
    unsigned num ;
    std::cout << "Enter num: " ;
    std::cin >> num ;

    doBinaryJunk(num) ;
}


This code outputs number of 1s and 0s but how to find position of 1s and 0s??
Last edited on
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
29
30
31
32
33
34
35
#include <iostream>
#include <bitset>
#include <limits>
#include <vector>

std::size_t position_of_lsb_that_is_set( unsigned int number )
{
    // http://en.cppreference.com/w/cpp/utility/bitset
    std::bitset< std::numeric_limits<unsigned int>::digits > bitset(number) ;
    std::cout << number << ' ' << std::showbase << std::hex << number << ' ' << bitset << std::dec << '\n' ;

    for( std::size_t pos = 0 ; pos < bitset.size() ; ++pos ) if( bitset[pos] ) return pos ;

    return std::size_t(-1) ; // no bit is set
}

std::vector<std::size_t> positions_of_set_bits( unsigned int number )
{
    std::vector<std::size_t> positions ;
    std::bitset< std::numeric_limits<unsigned int>::digits > bitset(number) ;

    for( std::size_t pos = 0 ; pos < bitset.size() ; ++pos ) if( bitset[pos] ) positions.push_back(pos) ;
    return positions ;
}

int main()
{
    const unsigned int number = 0b01000011100110010000 ;
    const auto first_bit_that_is_set = position_of_lsb_that_is_set(number) ;

    std::cout << "position of lsb that is set: " << first_bit_that_is_set << '\n'
              << "bits at the following positions are set (lsb is at position 0): " ;
    for( std::size_t pos : positions_of_set_bits(number) ) std::cout << pos << ' ' ;
    std::cout << '\n' ;
}

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