Results 1 to 4 of 4

Thread: simple program

  1. #1
    Army Officer monkeyhead's Avatar
    Join Date
    Sep 2001
    Location
    Killeen, TX
    Posts
    2,760

    simple program

    take as input an integer, ie 15

    and output as binary...... 00001111

  2. #2
    Regular Member
    Join Date
    Aug 1999
    Posts
    341
    Any language in particular?

    Here's one way to do it in C++:

    Code:
    #include <iostream>  // cout stream
    #include <bitset>    // bitset class
    #include <cctype>    // atoi()
    
    #define BITS_PER_BYTE 8
    
    int main(int argc, char **argv){
    
      const size_t bit_width = sizeof(int) * BITS_PER_BYTE; // Width of type in bits
      int int_to_convert;                                   // Integer to convert
    
      // If no command line option, print usage message and bail...
      if(argc < 2){
    
        cout << "Usage:\n"
             << "  program_name <integer to convert>\n"
             << ends;
    
        exit(1);
    
      }  // End if
    
      // Get the command line option, convert it to a integer, and store it...
      int_to_convert = atoi( *(++argv) );
    
      // Declare a bitset with a width of bit_width bits
      // and a initial value of int_to_convert's bits (in reverse order)...
      bitset<bit_width> bitvec(int_to_convert);
    
      // Loop through, in reverse, and print each bit...
      for(size_t s = bit_width - 1; s != -1; s--)
        cout << bitvec[s];
    
      // Print a newline...
      cout << '\n' << ends;
    
      return 0;
    
    }  // End main()

  3. #3
    Army Officer monkeyhead's Avatar
    Join Date
    Sep 2001
    Location
    Killeen, TX
    Posts
    2,760
    java?

  4. #4
    The Folding General General_Jack_As's Avatar
    Join Date
    May 2002
    Location
    Phoenix, AZ
    Posts
    885
    I don't know a lot of java but from what I hear it is really similar to C++. Thats the way to do it in C. I wouldn't know about java though.
    God Bless America

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •