Page 1 of 1
how to output binary numbers by "cout"?
Posted: Mon Apr 10, 2006 1:47 pm
by ImLazy
I use this code, but failed.
Code: Select all
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int a = 1234;
cout << setbase(2) << a << endl;
return 0;
}
The output is still "1234".
Help.
Posted: Mon Apr 10, 2006 3:34 pm
by Krzysztof Duleba
http://www.dinkumware.com/manuals/reade ... ml#setbase
As you see, setbase supports only bases of 8, 10 and 16.
I'm not aware of any standard way of displaying binary numbers.
Posted: Mon Apr 10, 2006 5:40 pm
by Moha
Yes, there is no way to output binary numbers directly with cout.
Posted: Tue Apr 11, 2006 3:39 am
by ImLazy
Oh, I see.
Thanks.
Another question. This code:
Code: Select all
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int a = 1234;
cout.setf(ios::hex);
cout << a << endl;
cout << hex << a << endl;
return 0;
}
why the output is
Posted: Tue Apr 11, 2006 4:03 am
by Krzysztof Duleba
Calling cout.setf(ios::hex) sets the flag, but it doesn't unset the others. The result is that both ios::hex and ios::dec are set.
There is another flavour of setf method, it takes two arguments and replaces selected bits (first argument) under a mask (second argument). Example:
Code: Select all
cout.setf(ios::hex, ios::basefield);
This is equivalent to
Code: Select all
cout.flags((cout.flags() & ~ios::basefield) | (ios::hex & ios::basefield))
In fact (ios::hex & ios::basefield) is equal to ios::hex, I just wanted to give the general formula.
Posted: Thu Apr 13, 2006 4:34 pm
by ImLazy
Oh, I see. Thank you for your help and also for your telling me a good website.