Outputting numbers to the console in binary format.

Discussion in 'C++' started by mungey, Aug 25, 2004.

  1. mungey

    mungey Guest

    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.
    mungey, Aug 25, 2004
    #1
    1. Advertising

  2. mungey

    Joe C Guest

    "mungey" <> wrote in message
    news:...
    > 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.
    Joe C, Aug 25, 2004
    #2
    1. Advertising

  3. 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
    =?ISO-8859-1?Q?Ney_Andr=E9_de_Mello_Zunino?=, Aug 25, 2004
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ben Finney
    Replies:
    2
    Views:
    990
    Egor Bolonev
    Jun 30, 2003
  2. Egor Bolonev
    Replies:
    0
    Views:
    477
    Egor Bolonev
    Jun 30, 2003
  3. Serge Terekhoff
    Replies:
    0
    Views:
    643
    Serge Terekhoff
    Jun 30, 2003
  4. Nick Gilbert
    Replies:
    5
    Views:
    2,002
    Alexey Smirnov
    May 11, 2007
  5. Ken Starks
    Replies:
    4
    Views:
    346
    Ken Starks
    Jun 23, 2008
Loading...

Share This Page