Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Outputting numbers to the console in binary format. (http://www.velocityreviews.com/forums/t285204-outputting-numbers-to-the-console-in-binary-format.html)

mungey 08-25-2004 03:56 AM

Outputting numbers to the console in binary format.
 
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.

Joe C 08-25-2004 04:08 AM

Re: Outputting numbers to the console in binary format.
 

"mungey" <mungey@lycos.com> wrote in message
news:7b1d25c2.0408241956.5caa81bb@posting.google.c om...
> 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?= 08-25-2004 05:03 PM

Re: Outputting numbers to the console in binary format.
 
mungey wrote:

> 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,

--
Ney André de Mello Zunino


All times are GMT. The time now is 02:46 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.