Advertisement
Guest User

Untitled

a guest
Dec 12th, 2017
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <algorithm> // reverse
  2. #include <climits>   // CHAR_BIT
  3. #include <iostream>
  4. #include <sstream>
  5.  
  6. std::string binario(unsigned int n)
  7. {
  8.   //converte numero para string de bits
  9.    std::stringstream bitsInReverse;
  10.    //int nBits = sizeof(n) * CHAR_BIT;
  11.    unsigned int nBits = sizeof(n)*2.5;
  12.  
  13.    while (nBits-- > 0)
  14.    {
  15.       bitsInReverse << (n & 1);
  16.       n >>= 1;
  17.    }
  18.  
  19.    std::string bits(bitsInReverse.str());
  20.    std::reverse(bits.begin(), bits.end());
  21.    return bits;
  22. }
  23.  
  24.  
  25. struct Bin
  26. {
  27.   friend std::ostream& operator<<(std::ostream& os, const Bin& f);  
  28.   int a;
  29. }bin;
  30.  
  31. std::ostream &operator<<( std::ostream &saida, const Bin& f)
  32. {
  33.   int c(f.a);
  34.   //converte numero para string de bits
  35.    std::stringstream bitsInReverse;
  36.    //int nBits = sizeof(c) * CHAR_BIT;
  37.    unsigned int nBits = sizeof(c) * 3;
  38.  
  39.    while (nBits-- > 0)
  40.    {
  41.     bitsInReverse << (c & 1);
  42.     c >>= 1;
  43.    }
  44.  
  45.    std::string bits(bitsInReverse.str());
  46.    std::reverse(bits.begin(), bits.end());
  47.  
  48.    saida << bits;
  49.    return saida;
  50. }
  51.  
  52. int main()
  53. {
  54.     std::cout<< "\n\t127 em binario:     " << binario(127)
  55.              << "\n\t127 em octal:       " << std::oct << 127
  56.              << "\n\t127 em hexadecimal: " << std::hex << 127
  57.              << "\n\t127 em decimal:     " << std::dec << 127
  58.              << "\n\t127 em binario:     " << bin<<127<<"\n\n";
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement