How to extract the bits from a binary number?

Hi,

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>

    using namespace 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;
} 
00000000000000000000000010001101
Last edited on
Wow thanks! And could you tell me how & and << works? I've never learned them. I just searched the this site but didn't find their definition.
In this context, << is the bitwise shift-left operator. It moves the integer (in its binary representation) one position to the left.

If you're not familiar with the operators, then you should take a look at the tutorial pages:
http://www.cplusplus.com/doc/tutorial/operators/

I'd also suggest looking here, as it gives more detail:
http://www.cprogramming.com/tutorial/bitwise_operators.html
Last edited on
Thanks a lot!
Topic archived. No new replies allowed.