Thread: naive print bits function

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jul 2012
    Posts
    87

    naive print bits function

    I'm getting an infinite loop. I want to print from MSB to LSB. I'm not sure why its stuck...

    Code:
    #include <climits>
    #include <iostream>
    
    using namespace std;
    
    template<typename t>
    //Q: how do I print it from MSB to LSB
    void print_bits(const t& type)
    {
        unsigned int mask;
        size_t num_bits = sizeof(t) * CHAR_BIT;
        size_t width = 0;
        
        for ( size_t i = (num_bits - 1); i >= 0; --i )
        {
            mask = type & ( 1 << i);//turn off all bits except cur bit 
            
            if ( !mask )//=> if 0(base-10) it means cur bit is 0 (when cur bit is AND 1)where we turn off all bits, then output '0'
                cout << mask;
            else
                cout << 1;//b/c if it's non-zero in base-2, then output binary 1
                
            if ( width % 4 == 3 )
                cout << " ";//to separate into 4bit chunks for readability
            ++width;
        }
        cout << endl;
    }
    
    int main()
    {
     unsigned int garage = 90;
     cout << "Status of each garage..." << endl;
     print_bits(garage);
    
     return 0;
    }
    It outputs it correctly as: 0000 0000 0000 0000 0000 0000 0101 1010 (for base-10 of 90), but then repeats, why?
    Last edited by monkey_c_monkey; 07-31-2012 at 04:46 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 15
    Last Post: 06-13-2012, 12:34 PM
  2. Passing a byte and its bits to a function
    By rtarbell in forum C Programming
    Replies: 9
    Last Post: 12-04-2008, 09:24 AM
  3. how to print bits?
    By majoub in forum C Programming
    Replies: 5
    Last Post: 03-19-2005, 12:15 PM
  4. print first and print last function
    By RawleyMacias in forum C Programming
    Replies: 6
    Last Post: 02-14-2002, 10:28 PM
  5. Function displaying bits...
    By Nutshell in forum C Programming
    Replies: 11
    Last Post: 01-27-2002, 11:34 AM