Hi Daniel!
Ich gebe meinen Senf in C++ auch noch dazu:
#include <iostream>
#include
using namespace std;
/* prueft, ob Bit j in Integer i gesetzt ist */
bool
isBitSet(const int i, const int j) {
return((i & (1 << j)) != 0);
}
/* zaehlt alle gesetzten Bits in Integer i */
int
countSetBits(const int i) {
int counter = 0;
int cmp = 1;
while(cmp != 0) {
if((i & cmp) != 0) {
++counter;
}
cmp <<= 1;
}
return counter;
}
/* setzt die bools in bitset so wie sie in i gesetzt sind */
int
getBitset(const int i, bool* bitset) {
int j = 0;
for(int cmp = 1; cmp != 0; j++) {
bitset[j] = ((i & cmp) != 0)? true : false;
cmp <<= 1;
}
return j;
}
/* gibt bitset der Laenge len aus */
void
printBitset(const bool* bitset, const int len) {
int i = 0;
for(; i < len; i++) {
cout << bitset[i];
}
if(i > 0) {
cout << endl;
}
}
int
main(const int argc, const char** argv) {
cout << "isBitSet(5, 0): " << isBitSet(5, 0) << endl;
cout << "isBitSet(5, 1): " << isBitSet(5, 1) << endl;
cout << "isBitSet(5, 2): " << isBitSet(5, 2) << endl;
cout << "countSetBits(5): " << countSetBits(5) << endl;
bool* bitset = new bool[sizeof(int) * CHAR_BIT];
printBitset(bitset, getBitset(5, bitset));
delete[] bitset;
return 0;
}
Ausgabe:
isBitSet(5, 0): 1
isBitSet(5, 1): 0
isBitSet(5, 2): 1
countSetBits(5): 2
10100000000000000000000000000000
hth,
Michael