Overload of Operator in C++

Asked

Viewed 107 times

-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 do to the operator of an istream and ostream so that it is possible

int c=10;
int d;

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

or

 std::bin>>d;
  • the question is poorly worded but it is interesting

1 answer

0


Your question is confused but I think I understand what you want: you want to create a Manipulator (this is the technical term) called bin, converting a number to binary, in the same way as manipulators Hex and Oct convert to hexadecimal and octal.

I thought I knew how to do it, but the way I did it didn’t work. By researching the subject I discovered that it is much complicated. A step-by-step recipe for how to do this here.

A simpler way to do this (though not the way you want) is simply to use a function to convert a number to a bit string, 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;

}

Other way: use bitset.

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

int main()
{
   int i = 10;
   cout << bitset<8>(i) << endl;
}
  • this exactly this but with Operator << in relation to the article from where read I have been seeing some other but I could not do and alias but would have to limit the zeros to type left in 8 in the case of function bin?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.