Thread: Binary Sequence

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    1

    Binary Sequence

    Hello,

    Does anyone know how to count the number of 1's and 0's in a binary sequence.

  2. #2
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    You can put it in a bitset and use the count member function

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    If it happens to already be in a string/character-array form you could also use the STL count_if function.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    Quote Originally Posted by hk_mp5kpdw
    If it happens to already be in a string/character-array form you could also use the STL count_if function.
    or just the std::count() see last example:

    Code:
    #include <bitset>
    #include <string>
    #include <iostream>
    #include <algorithm>
    
    const unsigned number = 15122;
    
    int countBits(unsigned n)
    {
        unsigned count = 0;
        while(n)
        {
            if (n&1)count++;
            n = n>>1;
        }
        return count;
    }
    int main()
    {    
        std::string str = std::bitset<32>(number).to_string();
    
        std::cout << countBits(number) << "\n";
        std::cout << std::bitset<32>(number).count() << "\n";
        std::cout << std::count(str.begin(), str.end(),'1')<< "\n";
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Immediate programming help! Please!
    By xMEGANx in forum C++ Programming
    Replies: 6
    Last Post: 02-20-2008, 12:52 PM
  2. Replies: 0
    Last Post: 11-04-2006, 11:07 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. Tutorial review
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 03-22-2004, 09:40 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM