Operator overload in C ++

-2

I have the program below:

#include <iostream>
#include <sstream>

namespace std
{
 int bin(int n)
 {  
  if(n!=0)bin(n/2);
  if(n!=0)std::cout<<n%2;
 } 
}

int main()
{    
    int n;
    std::istringstream("2a") >> std::hex >> n;

   std::cout << "Number 42 in octal:   " << std::oct << 42 <<"\n"
             << "Number 42 in decimal: " << std::dec << 42 <<"\n"
             << "Number 42 in hex:     " << std::hex << 42 <<"\n"
             << std::dec << "Hexa 2a in decimal:   " << n << '\n';

             //std::cout<< "Number 42 in bin:     " << std::bin << 42 <<"\n";

             //std::cout<< "Number 42 in bin:     " << std::bin>> 42 <<"\n";

    return 0; 
} 

how to make istream and ostream operator overload so that it is possible

int c=10;
int d;

std::bin<<c<<std::endl;
std::bin<<10<<std::endl;

or

 std::bin>>d;
    
asked by anonymous 22.02.2017 / 21:22

1 answer

0

Your question is confusing but I think I understand what you want: you want to create a manipulator (this is the technical term) called bin , which converts a number to binary, in the same way that the hex and oct manipulators convert to hexadecimal and octal.

I thought I knew how to do it, but the way I did it did not work. While researching the subject I found it to be very complicated. A step-by-step recipe on how to do this is here .

A simpler way to do this (though not the way you want it) is to simply use a function to convert a number to a string of bits, as in the example below.

#include <algorithm> // reverse
#include <climits>   // CHAR_BIT
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

string bin(int n)
{
   ostringstream bitsInReverse;
   int nBits = sizeof(n) * CHAR_BIT;

   while (nBits-- > 0)
   {
      bitsInReverse << (n & 1);
      n >>= 1;
   }

   string bits = bitsInReverse.str();
   reverse(bits.begin(), bits.end());
   return bits;
}

int main()
{
   cout << "42 em octal:       " << oct     << 42 << endl;
   cout << "42 em decimal:     " << dec     << 42 << endl;
   cout << "42 em hexadecimal: " << hex     << 42 << endl;
   cout << "42 em binario:     " << bin(42) << endl;

}

Another way: to use bitset.

#include <bitset>
#include <iostream>
using namespace std;

int main()
{
   int i = 10;
   cout << bitset<8>(i) << endl;
}
    
04.03.2017 / 04:43