Advertisement
Steefmaester

Bitset et conversion

Dec 3rd, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. //by steef
  2. #include <iostream>
  3. #include <iomanip>
  4. #include <bitset>
  5. #include <string>
  6.  
  7. using namespace std;
  8.  
  9. const int format_bit = 16;//valeur max->32 car sizeof(bitset<X>) sera toujours égale à 4 octets(32bits) !
  10.  
  11. int bit2dec(string valeur)
  12. {
  13.     bitset<format_bit> bit(valeur);
  14.     int dec;
  15.  
  16.     if (valeur.at(0) == '1') // si valeur est négative
  17.     {
  18.         //complément à 2 :
  19.         dec = bit.to_ulong() - 1;
  20.         bit = dec;
  21.         bit = ~bit;
  22.         dec = -1 * bit.to_ulong();
  23.     }              
  24.     else dec = bit.to_ulong(); // si valeur positive
  25.    
  26.     return dec;
  27. }
  28.  
  29.  
  30. void main() {
  31.  
  32.     int nb = 255;
  33.  
  34.     bitset<format_bit> test = nb;//initialisé un bitset avec un int (marche aussi avec un string)
  35.     cout << test << endl;
  36.  
  37.     string test2 = test.to_string() ; //convertir un bitset en string
  38.     cout << test2 << endl;
  39.  
  40.     test = static_cast<bitset<format_bit>>(nb | ~nb);//caster un int en bin
  41.     cout << test << endl << endl;
  42.  
  43.  
  44.     test = -255;
  45.     nb = test.to_ulong(); //convertir un bitset en unsigned long
  46.     cout << nb << endl; // -> ne fonctionne donc pas avec les valeurs négatives
  47.  
  48.     nb = bit2dec(test.to_string());//convertir un bitset en int
  49.     cout << nb << endl; // -> fonctionne aussi avec les valeurs négatives (le bit de poid fort = signe)
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement