how to output binary numbers by "cout"?

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

how to output binary numbers by "cout"?

Post 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.
I stay home. Don't call me out.
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post 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.
Moha
Experienced poster
Posts: 216
Joined: Tue Aug 31, 2004 1:02 am
Location: Tehran
Contact:

Post by Moha »

Yes, there is no way to output binary numbers directly with cout.
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Post 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

Code: Select all

1234
4d2
I stay home. Don't call me out.
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post 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.
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Post by ImLazy »

Oh, I see. Thank you for your help and also for your telling me a good website.
I stay home. Don't call me out.
Post Reply

Return to “C++”