Sign in to follow this  
Rhaal

How do you "check" bit flags?

Recommended Posts

I'm getting stuck at the basics again. How do you check bits in a bit flag? My program successfully iterates through files, but now I'm trying to skip over directories and archives. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/win32_find_data_str.asp Obviously, == is not the right operator. This is what I tried:
FindNextFile(hFind, &FindFileData);
if(&FindFileData.dwFileAttributes == FILE_ATTRIBUTE_ARCHIVE)
{
  FindNextFile(hFind, &FindFileData);
}

Share this post


Link to post
Share on other sites
Explanation:

Say dwFileAttributes is 10010110 binary.
Now, assume FILE_ATTRIBUTE_ARCHIVE is 00010000.

& is the bitwise AND operator, so (1 & 1 = 1), (1 & 0 = 0), (0 & 1 = 0), and (0 & 0 = 0). If you do this on a string of bits, such as dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE, you get:
  10010110
& 00010000
----------
= 00010000

which is non-zero, which evaluates to true upon conversion to bool.

If FILE_ATTRIBUTE_ARCHIVE had been 01000000, then:
  10010110
& 01000000
----------
= 00000000

which is zero, which evaluates to false upon conversion to bool.



jfl.

Share this post


Link to post
Share on other sites
Quote:
Original post by Timjanmannen
if(bitset&&flag) equals to true as long as 'bitset' and 'flag' is not 0

i might not remeber correctly, but i think it was something like if((bitset&flag)==flag)


(bitset & flag) will result in a non-zero value if the flag is set and in a zero value if the flag isn't set. In C++ it would be sufficient to do this:
if(bitset & flag) { }
as non-zero values evaluate to true and zero values evaluate to false.

EDIT: jflanglois's post comes down to the same thing, but is way better

Share this post


Link to post
Share on other sites
I see now. The problem was it didn't compile with '&' because I was doing this:

if(&FindFileData.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)

Instead of:
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)

.. meaning I was trying to check the address of the find file data and not the data itself, right?

Share this post


Link to post
Share on other sites
Well, yes and no. It probably failed because DWORD * is an invalid type for operator&. If it were to work, though (i.e. if you had cast the left side to DWORD), then the problem would indeed be that you were ANDing the address of dwFileAttributes with the value of FILE_ATTRIBUTE_ARCHIVE. It would compile, though.


jfl.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this