Thread: naive print bits function

  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.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    size_t is an unsigned type -> your condition i >= 0; is alwais true
    try
    Code:
    for ( int i = (num_bits - 1); i >= 0; --i )
    Kurt

  3. #3
    Registered User
    Join Date
    Jul 2012
    Posts
    87
    Why would changing it from size_t (unsigned int) to int stop the infinite loop? It works, but why though?
    Last edited by monkey_c_monkey; 07-31-2012 at 04:55 PM.

  4. #4
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    You have to use a signed type or put
    Code:
     if ( i == 0 )
        break;
    at the and of the loop
    Kurt

  5. #5
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    an unsigned type never has a value lower then 0.
    Kurt

  6. #6
    Registered User
    Join Date
    Jul 2012
    Posts
    87
    I thought unsigned type was from: 0 to (2^n) - 1 where n is the data type's number of bits needed to store it. so int is 32bits so the range is from: 0 to (2^32) - 1

  7. #7
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    the condition i >= 0; is false only when the value is < 0.
    Kurt

  8. #8
    Registered User
    Join Date
    Jul 2012
    Posts
    87
    ok I get it now, 0 is smallest with unsigned, I wasn't thinking...

  9. #9
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Here's all the ways I can think of fixing it.
    Code:
    for (int i = numbits - 1; i >= 0; i--)
    {
        ifunc(i);
    }
    
    for (size_t i = numbits - 1; i != size_t(-1); i--) // is this always safe?
    {
        ifunc(i);
    }
    
    for (size_t i = numbits - 1;  1;  i--)
    {
        ifunc(i);
        if (i == 0)
            break;
    }
    
    size_t i = num_bits;
    do {
        --i;
        ifunc(i);
    } while (i != 0);
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  10. #10
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    The most common (and safe) way of solving it that I've seen is:
    Code:
    for (size_t i = numbits; i-- > 0;)
    oogabooga, your third one fails when numbits is zero.
    And for your second one, I had a feeling that unsigned overflow was okay, but that unsigned underflow was still UB.
    Last edited by iMalc; 08-01-2012 at 02:11 AM.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  11. #11
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    By the way, if you used a higher warning level setting in your compiler (and you should), it should have warned you about this. I get this warning all the time. Saved me a lot of time over the years.

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    A bit cryptic perhaps, but I get the warning
    Warning 11 warning C4702: unreachable code
    on the original code using Visual Studio.
    It doesn't complain about the infinite loop, but it definitely detects the infinite loop.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    Hmm I can't seem to generate the warning now on GCC, but I've definitely seen it before.

  14. #14
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I still prefer to iterate over a mask as done here on lines 11 and 27. The loop control is straight forward: bit > 0 is equivalent to what is written for the condition.

  15. #15
    Registered User
    Join Date
    Aug 2012
    Location
    Venezuela
    Posts
    1
    Hello cyberfish, how may i be in touch with you? I like your desktop streamer project

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