Sign in to follow this  
DarkSlayer

cout a int in binary form

Recommended Posts

I have an int int t = 4; the binary representation is: 100 how can I cout this t as 100? even better, let say I have an int or whatever, and I know the length of the binary representation, like t = 46, which has a length of 6 digits. How can I use the length to print the binary representation. Sometimes you do want to print some of the zero's in the front

Share this post


Link to post
Share on other sites

#include <iostream>

void coutNumberAsBinary( int number )
{
//buffer big enough to hold a 32-bit number + 1 char for null termination of the string
char outStr[33];
itoa( number, outStr, 2);
std::cout << outStr;
}






for explaination of itoa see:
http://www.cplusplus.com/ref/cstdlib/itoa.html (found with google: itoa)

-me

Share this post


Link to post
Share on other sites
[attention][attention][attention]
char * itoa ( int value, char * buffer, int radix );
...
Portability.
Not defined in ANSI-C. Supported by some compilers.
[attention][attention][attention]


#include <bitset>
#include <iostream>

int main()
{
std::cout << std::bitset<8>(4) << std::endl;
}



Quote:
t is my integer I want to print, and 1 << i ... is it bit shift? bitshift 1, i times to the left?
uh...


Yes.

Share this post


Link to post
Share on other sites
Ansi C isn't that differnt from c++? Isn't ansi c the good old c language? If that's so I don't care too much about it for now (probably not anyway, but nice to know).

((1 << i) & t) ? "1" : "0";

or
((1 << i) & t)

in the first loop where i = 7
1 is shifted to the left 7 times from 00000001 to 10000000? correct?
Then what would (10000000 & t) do, and how would that become true or false?

Share this post


Link to post
Share on other sites
Quote:
Original post by DarkSlayer
Then what would (10000000 & t) do


bitwise-and

Quote:
and how would that become true or false?


zero is false, any non-zero is true.


You're also more likely to want to output '1' and '0' instead of "1" and "0" (why gratuitously make things slower ?)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this