bit_and function in C++
Last Updated :
10 May, 2019
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:
#include <algorithm> // transform
#include <functional> // bit_and
#include <iostream> // cout
#include <iterator> // end
using namespace std;
int main()
{
int xyz[] = { 500, 600, 300, 800, 200 };
int abc[] = { 0xf, 0xf, 0xf, 255, 255 };
int n = 5;
int results[n];
transform(xyz, end(xyz), abc,
results, bit_and< int >());
cout << "Results:" ;
for ( const int & x : results)
cout << ' ' << x;
return 0;
}
|
Output:
Results: 4 8 12 32 200
Program-2:
#include <algorithm> // transform
#include <functional> // bit_and
#include <iostream> // cout
#include <iterator> // end
using namespace std;
int main()
{
int xyz[] = { 0, 1100 };
int abc[] = { 0xf, 0xf };
int results[2];
transform(xyz, end(xyz), abc,
results, bit_and< int >());
cout << "Results:" ;
for ( const int & x : results)
cout << ' ' << x;
return 0;
}
|
Share your thoughts in the comments
Please Login to comment...