access to bit from integer : a good way ?

I want to access a specific bit (say n) from an integer b;

Using bitset class, this can be handle with :

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <bitset>

using namespace std;

int main () {
 int b=10,n=3;
 bitset<4> bit(b); // 1010
 cout << bit[n]; // 0
 return 0;
}

However, I want to perform this operation often (e.g. in a loop), without having to allocate dynamically the memory with constructor...

What is a good/optimized way to do that ?
Is dynamical allocation a bad way to do that ?

Thank you!
Is there any particular reason why you don't want to use dynamic allocation to allocate an arbitrary number of bitsets?

-Albatross
Well, doesn't it slow that calculation ?
I mean, perhaps there is another easy way to do that, which does not require dynamic allocation...?

-UsherbPhys
Hold on. Am I seeing correctly that the only thing you want to do in this program is get the nth bit of a given integer? If so, why not use a bitwise and operator and a well-chosen integer to mask out all the bits except the one(s) you want?

-Albatross
Oh, your right, that's the easiest way ! Thanks

-USherbPhys
Topic archived. No new replies allowed.