Outputting numbers to the console in binary format.

M

mungey

Hi,

How can I output an integral number to the console in binary format?

E.g. instead of:

69

I need.

1000101

Can it be achieved with a standard procedure call such as fprintf() or
something ilke that?

Thanks.
 
J

Joe C

mungey said:
Hi,

How can I output an integral number to the console in binary format?

E.g. instead of:

69

I need.

1000101

Can it be achieved with a standard procedure call such as fprintf() or
something ilke that?

Thanks.

You need to roll your own. You could use something like:
_______________
#include <iostream>

void printBinary(const unsigned int val) {
for(int i = sizeof(unsigned int) * CHAR_BIT; i >= 0; i--)
if(val & (1 << i))
std::cout << "1";
else
std::cout << "0";
}


int main(){
unsigned int a= 436;
printBinary(a);
}
_____________

the function came from Bruce Eckel, not me...There are exactly one zillon
ways to do the same.
 
?

=?ISO-8859-1?Q?Ney_Andr=E9_de_Mello_Zunino?=

mungey said:
How can I output an integral number to the console in binary format?

E.g. instead of:

69

I need.

1000101

The easiest way is through the use of std::bitset<>, e.g. (untested):

#include <bitset>
#include <iostream>

int main()
{
int i = 69;
std::cout << std::bitset<8>(i);
}

Regards,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top