# cout a int in binary form

## Recommended Posts

DarkSlayer    100
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 on other sites
Tim Cowley    340
int bits = sizeof(int) * 8; //prolly 32for (int i = (bits - 1); i >= 0; --i)  cout << ((1 << i) & t) ? "1" : "0";

edit: whoops

##### Share on other sites
DarkSlayer    100
aha - I see what you mean

just to get it right:
what means
((1 << i) & t)

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

##### Share on other sites
Palidine    1315
#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:

-me

##### Share on other sites
DarkSlayer    100
even better - brilliant

but anybody answear my previous question? It's nice to know anyway..

thx ppl, always an answear to everyday problems at gamedev

##### Share on other sites
Fruny    1658
[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 on other sites
DarkSlayer    100
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 on other sites
Fruny    1658
Quote:
 Original post by DarkSlayerThen 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 on other sites
DarkSlayer    100
ah ... now I get it ... cool

I couln't understand why the & was there for

ofcourse

thx ppl