bit_and function in C++

bit_and is a builtin function in C++ which is used to return the values after applying the bitwise_and on its arguments(as returned by operator &).

template  struct bit_and 
{
  T operator() (const T& a, const T& b) const {return a&b;}
  typedef T type of first_argument;
  typedef T type of second_argument;
  typedef T result_type;
};

T is the type of all the arguments.

Note:

  1. Objects of this class can be used on standard algorithms such as transform or accumulate.
  2. Member functions ( ‘operator()’ ) returns the bitwise_and of its arguments.

We must include the library ‘functional’ and ‘algorithm’ to use bit_and and transform respectively otherwise they will not work.

Below are the programs to show the working of bit_and function:
Program-1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to show the 
// functionality of bit_and
#include <algorithm> // transform
#include <functional> // bit_and
#include <iostream> // cout
#include <iterator> // end
using namespace std;
  
int main()
{
    // declaring the values
    int xyz[] = { 500, 600, 300, 800, 200 };
    int abc[] = { 0xf, 0xf, 0xf, 255, 255 };
    int n = 5;
    // defining results
    int results[n];
  
    // transform is used to apply
    // bitwise_and on the arguments
    transform(xyz, end(xyz), abc,
              results, bit_and<int>());
  
    // printing the resulting array
    cout << "Results:";
    for (const int& x : results)
        cout << ' ' << x;
  
    return 0;
}

chevron_right


Output:

Results: 4 8 12 32 200

Program-2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to show the 
// functionality of bit_and
#include <algorithm> // transform
#include <functional> // bit_and
#include <iostream> // cout
#include <iterator> // end
using namespace std;
  
int main()
{
    // declaring the values
    int xyz[] = { 0, 1100 };
    int abc[] = { 0xf, 0xf };
  
    // defining results
    int results[2];
    // transform is used to apply
    // bitwise_and on the arguments
    transform(xyz, end(xyz), abc,
              results, bit_and<int>());
  
    // printing the resulting array
    cout << "Results:";
    for (const int& x : results)
        cout << ' ' << x;
  
    return 0;
}

chevron_right


Output:

Results: 0 12


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : shubham_singh



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.