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:
- Objects of this class can be used on standard algorithms such as transform or accumulate.
- 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:
// 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; } |
Output:
Results: 4 8 12 32 200
Program-2:
// 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; } |
Output:
Results: 0 12
Contact Us