Re: Bits in integer-Wert
Tobias Erbsland <[email protected]>
| Newsgroups | gmane.linux.suse.programming |
|---|---|
| Organization | PrintSoft (Schweiz) AG |
| Message-ID | <[email protected]> |
Hallo
> #include <bitset>
> #include <iostream>
>
> using namespace std;
Wo unterrichtet man denn dieses "using namespace std;" ? Der Namensbereich std
hat man zur Unterscheidung zwischen eigenen Funktionen und Variablen und der
standard Bibliothek eingeführt.
#include <iostream>
int main( int argc, char* argv[] )
{
const int x = 42;
for( int i = sizeof(x)*8-1; i >= 0; i-- )
{
std::cout << ((x & (2<<i)) > 0);
}
std::cout << std::endl;
return 0;
}
Bis auf die Ausgabe ist das eine reine C Lösung.
> #define N 32
>
> int main(void) {
> bitset<N> b = 5; // oder bitset<N> b; cout << "zahl: "; cin >> b;
> int bitsset;
> for(register unsigned int i = 0; i < N; i++) {
> if( b[i] ) { bitsset++; }
> }
> cout << bitsset << endl;
> return 0;
> }
Das ist eher ein C++ Ansatz, jedoch deutet die for Schleife und viel schlimmer
das #define noch auf den eingefleischten C Programmierer hin. Wenn schon die
STL dann richtig:
#include <iostream>
#include <bitset>
int main( int argc, char* argv[] )
{
const int x = 42;
std::bitset<sizeof(x)*8> x_bits( x );
std::cout << "Number of bits set: " << x_bits.count() << std::endl;
std::cout << "Binary representation: " << x_bits << std::endl;
return 0;
}
Gruss
Tobias
--
Um die Liste abzubestellen, schicken Sie eine Mail an:
[email protected]
Um eine Liste aller verfügbaren Kommandos zu bekommen, schicken
Sie eine Mail an: [email protected]