Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Bit Display.

  1. Sep 15, 2004 #1
    PHP:

    mask =  0x80;
    for(i = 0; i < 8; i++)
    {
        if((testvalue & mask)!= 0)
                {          
                    cout<<"1";
                }
        else
                {
        cout<<"0";
                }
        mask = mask >> 1;

    }
     
    The code displayed was for displaying the bits in a char,however it doesn't work. Please help me with the code.
    Thanx.
     
  2. jcsd
  3. Sep 15, 2004 #2

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Is this homework?

    This code appears by inspection to be correct. Is mask the same data type as testvalue?

    - Warren
     
  4. Sep 15, 2004 #3
    PHP:
    char testvalue,mask ;
    No it isnt HW.
     
  5. Sep 15, 2004 #4
    PHP:

    for(i = 0; i < 8; i++)
    {
          if((test & 0x80)!= 0)
          {
           cout<<"1";
          }
          else
          {
           cout<<"0";
          }
        test = test << 1;

     }
     
    This code works well however the testvalue is altered. I didnt want that to happen ,and I therefore wrote the code displayed in post1, where the mask is shifted.
     
  6. Sep 15, 2004 #5
    Please be more specific: what exactly doesn't work? As chroot said, the code looks OK.
     
  7. Sep 15, 2004 #6
    You might find this code interesting (this is how I'd probably write it, I'd just add some more checks in real code).

    Code (Text):

    #include <iostream>
    #include <cassert>

    using namespace std;

    template <typename T>
    void print_bits(const T& value, int to_go = sizeof(T) * 8)
    {
            if (to_go == 0) return;
            assert (to_go > 0);
            bool last = value & T(1);
            print_bits(value >> 1, to_go - 1);
            cout << last;
    }

    int main()
    {
            print_bits('a'); cout << endl;
            print_bits(-17); cout << endl;
            print_bits(unsigned(-17)); cout << endl;
            print_bits(short(-17)); cout << endl;
    }
    Run it and see what it prints. BTW, I think the "*8" part is not guaranteed by the standard to be portable but I don't know any platform where this would be a problem.
     
  8. Sep 15, 2004 #7
    Ah, I know why it doesn't work! if you declared "mask" as "char" then 0x80 is actually a negative value and the sign bit is preserved. you should have written those declarations in the first piece of code :) I've barely nticed you mantioned it latter.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Bit Display.
  1. Display Problems ` (Replies: 0)

  2. RGB display ? (Replies: 3)

  3. Display settings (Replies: 2)

  4. Bits and bytes (Replies: 2)

Loading...