understand masking bits

This is a discussion on understand masking bits within the C++ Programming forums, part of the General Programming Boards category; Hi there, I am not quite understanding why the program described at Question11-1 from (Page 169) is working - I ...

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    16

    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 -----


    Code:
    #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
    Posts
    7,325
    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
    Posts
    52
    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, 02: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, 12:43 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21