Jump to content

Get bit flags without looping through all possible values?


Josh
 Share

Recommended Posts

Let's say I have an unsigned integer I am storing bitwise flags in. I can store up to 32 possible flags.

Without looping through 64 values, is there a mathematical way I can retrieve which flags are set from the total number?:

bool flag[64] = { false };
for (int i=0; i<64; ++i)
{
  if ((i^2) & flags) flag[i] = true;
}

I expect the number of flags to be set to be fairly small, like 1-3, thus I want to avoid the loop.

My job is to make tools you love, with the features you want, and performance you can't live without.

Link to comment
Share on other sites

Not sure if this is what your asking? Sorry if not

 

.h
enum
{
	kFlag1 1 << 0,
	kFlag2 1 << 1,
	kFlag3 1 << 2
};

class Foo
{
private:
	long 	flags;
public:

	Foo();
}


.cpp
Foo::Foo()
{
	//set some flags
	flags |= kFlag1 | kFlag2;

	//remove flag
	flags &= ~kFlag1;
}

Foo::Test(long flag)
{
	//check flag is set in variable
	if(flag & kFlag1)
	{
	}

	//check flag is not set in variable
	if(!(flag & kFlag1))
    {
    }
}

 

trindieprod.png?dl=0spacer.png?dl=0steam-icon.png?dl=0twitter-icon.png?dl=0spacer.png?dl=0
Link to comment
Share on other sites

No, the problem is this code goes in a pixel shader and I don't want to go through in a loop and test each possible value when only a few of them will be true.

This might be right:

int flags = 1||4|16|256|4096|16384;
bool setflags[32] = {false};
while (flags > 0)
{
	int log2 = Log2(flags);
	setflags[ log2 ] = true;
	flags -= Pow2(log2);
}

 

My job is to make tools you love, with the features you want, and performance you can't live without.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...