Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //by steef
- #include <iostream>
- #include <iomanip>
- #include <bitset>
- #include <string>
- using namespace std;
- const int format_bit = 16;//valeur max->32 car sizeof(bitset<X>) sera toujours égale à 4 octets(32bits) !
- int bit2dec(string valeur)
- {
- bitset<format_bit> bit(valeur);
- int dec;
- if (valeur.at(0) == '1') // si valeur est négative
- {
- //complément à 2 :
- dec = bit.to_ulong() - 1;
- bit = dec;
- bit = ~bit;
- dec = -1 * bit.to_ulong();
- }
- else dec = bit.to_ulong(); // si valeur positive
- return dec;
- }
- void main() {
- int nb = 255;
- bitset<format_bit> test = nb;//initialisé un bitset avec un int (marche aussi avec un string)
- cout << test << endl;
- string test2 = test.to_string() ; //convertir un bitset en string
- cout << test2 << endl;
- test = static_cast<bitset<format_bit>>(nb | ~nb);//caster un int en bin
- cout << test << endl << endl;
- test = -255;
- nb = test.to_ulong(); //convertir un bitset en unsigned long
- cout << nb << endl; // -> ne fonctionne donc pas avec les valeurs négatives
- nb = bit2dec(test.to_string());//convertir un bitset en int
- cout << nb << endl; // -> fonctionne aussi avec les valeurs négatives (le bit de poid fort = signe)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement