How to display integer to binary format?

This is a discussion on How to display integer to binary format? within the C++ Programming forums, part of the General Programming Boards category; Does anyone has code on how to display an interger into its binary format? Thanks!!!...

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    163

    How to display integer to binary format?

    Does anyone has code on how to display an interger into its binary format? Thanks!!!

  2. #2
    C/C++Newbie Antigloss's Avatar
    Join Date
    May 2005
    Posts
    212
    Code:
    #include <iostream>
    #include <stack>
    #include <cstddef>
    
    using std::cin;
    using std::cout;
    using std::stack;
    
    int main()
    {
        short x = -4;
        size_t i = sizeof(short) * 8; // short 的位数
       short a = 1;
        stack<short> bin;
    
        for ( size_t j = 0; j != i; ++j ) {
            bin.push( x & a );
            x >>= 1;
        }
        while ( !bin.empty() ) {
            cout << bin.top() ;
            bin.pop();
        }
    
        cout << "\nPress ENTER to quit...";
        cin.get();
        return 0;
    }

  3. #3
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Converting Text to Binary (And Back)
    Binary Converter - Various stupid string issues :p
    Decimal to binary but doesn't work

    etc. etc. etc. etc. It gets discussed pretty frequently. Why would one ever want to do such an insane thing as this?

  4. #4
    Registered User
    Join Date
    Dec 2004
    Posts
    163
    Antigloss, your code is really useful! Thanks for your help! =)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how integer stored in binary format in 'c' language
    By pankaj_kumar in forum C Programming
    Replies: 7
    Last Post: 04-01-2009, 08:26 AM
  2. integer to binary
    By rs07 in forum C Programming
    Replies: 2
    Last Post: 09-17-2008, 12:18 AM
  3. integer format question
    By fsu_altek in forum C++ Programming
    Replies: 4
    Last Post: 10-11-2005, 05:31 PM
  4. display tree data in binary tree format
    By xddxogm3 in forum C++ Programming
    Replies: 4
    Last Post: 12-10-2003, 11:47 PM
  5. Aligning strings display format
    By Hexxx in forum C Programming
    Replies: 2
    Last Post: 11-03-2003, 09:51 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21