Thread: understand masking bits

  1. #1
    Registered User
    Join Date
    Jan 2006

    understand masking bits

    Hi there,

    I am not quite understanding why the program described at Question11-1 from (Page 169) is working - I am expecting it not to work. Might somebody please explain why.

    The result should 0 after masking after masking the bits in the line 'if ((flags & DIRECT_CONNECT) != 0)', right?

    --- output of program ---

    % ./question11-1
    High speed set
    Direct connect set

    ---- snip -----

    #include <iostream>
    const int HIGH_SPEED = (1<<7);      /* modem is running fast */
                                           // we are using a hardwired connection
    const int DIRECT_CONNECT = (1<<8);
    char flags = 0;
    int main()
      flags |= HIGH_SPEED;          // we are running fast  
      flags |= DIRECT_CONNECT;      // because we are wired together
      if ((flags & HIGH_SPEED) != 0)
        std::cout << "High speed set\n";
      if ((flags & DIRECT_CONNECT) != 0)
        std::cout << "Direct connect set\n";
      return (0);

  2. #2
    Registered User
    Join Date
    Jan 2005
    Why? The code turns on the DIRECT_CONNECT bit with the line: flags |= DIRECT_CONNECT; so it will return non-zero when you check for that bit later.

  3. #3
    Registered User
    Join Date
    Nov 2005
    Your bitwise & in the conditional doesn't modify the flags set in any way. The expression returns a temporary boolean variable that's evaluated (as true in this case) and then disappears. Since flags is never changed, it SHOULD report exactly what you see as the output.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. SDLKey to ASCII without unicode support?
    By zacs7 in forum Game Programming
    Replies: 6
    Last Post: 10-07-2007, 03:03 AM
  2. Help counting number of bits set in an integer
    By JayDiddums10 in forum C Programming
    Replies: 5
    Last Post: 12-07-2006, 03:21 PM
  3. Writing binary data to a file (bits).
    By OOPboredom in forum C Programming
    Replies: 2
    Last Post: 04-05-2004, 03:53 PM
  4. New idea on conveting byte to bits/bits to byte
    By megablue in forum C Programming
    Replies: 10
    Last Post: 10-26-2003, 01:16 AM
  5. Help Please...bits
    By Unregistered in forum C Programming
    Replies: 11
    Last Post: 01-24-2002, 01:43 PM