Binary Sequence

This is a discussion on Binary Sequence within the C++ Programming forums, part of the General Programming Boards category; Hello, Does anyone know how to count the number of 1's and 0's in a 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,803
    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, 11:52 AM
  2. Replies: 0
    Last Post: 11-04-2006, 10: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, 08:40 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21