I want a function that, given two integers n and k, returns the kth bit of the binary representation of n. Does C++ come with such a function? If yes, which library do I need? Thanks!
You just need to "and" the number n with an integer with just the required bit set on, like this: n & (1<<k)
Or consider the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int getBit(int n, int k)
{
return (n & (1<<k)) != 0;
}
int main()
{
int n = 141;
for (int k = 31; k>=0; k--)
cout << getBit(n,k);
cout << endl;
return 0;
}