Thread: How to display integer to binary format?

  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
    216
    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
    http://cboard.cprogramming.com/showt...ghlight=binary
    http://cboard.cprogramming.com/showt...ghlight=binary
    http://cboard.cprogramming.com/showt...ghlight=binary

    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-11-2003, 12:47 AM
  5. Aligning strings display format
    By Hexxx in forum C Programming
    Replies: 2
    Last Post: 11-03-2003, 10:51 PM