[C++] Niezrozumiały zapis
Ostatnio zmodyfikowano 2016-02-24 06:13
Lero Temat założony przez niniejszego użytkownika |
[C++] Niezrozumiały zapis » 2016-02-23 22:34:27 Witam. Znalazłem taki kod, który ma przeliczać liczby Dec na Bin. Wyjaśni mi ktoś jak on działa? string DecToBin2( int number ) { string result = ""; do { if(( number & 1 ) == 0 ) result += "0"; else result += "1"; number >>= 1; } while( number ); reverse( result.begin(), result.end() ); return result; }
Chodzi mi głownie o zapis (number & 1) == 0 |
|
Garniturek |
» 2016-02-23 23:14:40 ten warunek sprawdza czy 'number' jest równy 0. & to mnożenie logiczne. wszystko razy 0 da zero i tylko wtedy. Jeśli się mylę niech ktoś poprawi :D |
|
pekfos |
» 2016-02-24 00:10:09 Koniunkcja bitowa z 1 wyciąga z liczby wartość jej najmłodszego bitu. |
|
mateczek |
» 2016-02-24 06:13:53 #include <iostream> #include<string> #include<algorithm>
using namespace std;
string DecToBin2( int number ) { string result = ""; do { result +=( number & 1 ) + '0'; number >>= 1; } while( number ); reverse( result.begin(), result.end() ); return result; }
string func( int number, int base ) { string result = ""; do { int cyfra = number % base; if( cyfra >= 10 ) result +=( cyfra - 10 ) + 'A'; else result += cyfra + '0'; number /= base; } while( number ); reverse( result.begin(), result.end() ); return result; }
int main() { int numer = 199; cout << DecToBin2( numer ) << endl; cout << func( numer, 2 ) << endl; cout << func( numer, 10 ) << endl; cout << func( numer, 8 ) << endl; cout << func( numer, 16 ) << endl; cout << func( numer, 20 ) << endl; } |
|
« 1 » |