Archived

This topic is now archived and is closed to further replies.

Setting and unsetting bits

This topic is 5554 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Okay, I know this has been discussed many times, but the searchfunction is out of order I have also read the article about bitwise operations here on GD.net, but it did not answer my question. How do I write a function which sets bit in a mode-variable (int mode), and more important hod do i unset it? I want to be able to do: SetBit(MyMode,OBJECT_VISIBLE) And UnSetBit(MyMode, OBJECT_VISIBLE) My guesses are this:

void SetBit(int mode, int flag)
{
mode = mode | flag;
}

void UnSetBit(int mode, int flag)
{
//Flag set?

if(mode & flag)
mode = mode ^ flag;
}

But maybe there is a simpler answer, or maybe I am not correct at all?

Share on other sites
second function can be replaced with

mode = mode & ~flag;

which is more efficient because there's no jump.

or you can use

mode |= flag;

mode &= ~flag;

that's as easy as it gets.

and you want to pass mode by reference.

[edited by - niyaw on December 7, 2002 8:41:07 AM]

Share on other sites
quote:
Original post by niyaw ...and you want to pass mode by reference.
why?

uh... nevermind

Share on other sites
Thanks a lot!

It really helped.