Just starting out? Need help? Post your questions and find answers here.
Mistrel
Addict
Posts: 3415 Joined: Sat Jun 30, 2007 8:04 pm
Post
by Mistrel » Sun Oct 13, 2019 12:50 am
I have a set of flags that I want to test. I can't do the following because it will debug "1" for either TEST_A or TEST_B and not both exclusively:
Code: Select all
#TEST_A=1<<0
#TEST_B=1<<1
a|#TEST_A
If a&(#TEST_A|#TEST_B)
Debug 1
EndIf
I have to do this instead:
Code: Select all
If a&#TEST_A And a&#TEST_B
Debug 2
EndIf
Is there a way to test whether all flags exist in a single operation without having to use multiple checks in this way?
wilbert
PureBasic Expert
Posts: 3870 Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands
Post
by wilbert » Sun Oct 13, 2019 4:54 am
Mistrel wrote: Is there a way to test whether all flags exist in a single operation without having to use multiple checks in this way?
You can compare against the mask
Code: Select all
#TEST_A=1<<0
#TEST_B=1<<1
a = #TEST_A|#TEST_B
If a & (#TEST_A|#TEST_B) = #TEST_A|#TEST_B
Debug "Both flags are set"
EndIf
Windows (x64)
Raspberry Pi OS (Arm64)
BarryG
Addict
Posts: 3292 Joined: Thu Apr 18, 2019 8:17 am
Post
by BarryG » Sun Oct 13, 2019 5:12 am
Building on Wilbert's code, you can use a macro for less typing and better readability:
Code: Select all
#TEST_A=1<<0
#TEST_B=1<<1
Macro HasTheseFlags(f)
& (f) = (f)
EndMacro
If a HasTheseFlags(#TEST_A|#TEST_B)
Debug "Both flags are set"
EndIf
Last edited by
BarryG on Sun Oct 13, 2019 8:57 am, edited 1 time in total.
Mistrel
Addict
Posts: 3415 Joined: Sat Jun 30, 2007 8:04 pm
Post
by Mistrel » Sun Oct 13, 2019 6:41 am
Maybe I'm just getting old to be asking questions like this. Thank you all for putting up with my rants where I talk big and then come and ask silly questions like this.
It's been a while since I've worked with bit flags. I feel very spoiled by object-oriented enum classes and enum sets.
BarryG
Addict
Posts: 3292 Joined: Thu Apr 18, 2019 8:17 am
Post
by BarryG » Sun Oct 13, 2019 7:33 am
I'm just glad I could help! I don't use bits very often, so I'm shocked that my macro actually works.
STARGÅTE
Addict
Posts: 2067 Joined: Thu Jan 10, 2008 1:30 pm
Location: Germany, Glienicke
Contact:
Post
by STARGÅTE » Sun Oct 13, 2019 8:00 am
BarryG wrote:
I'm just glad I could help! I don't use bits very often, so I'm shocked that my macro actually works.
It doesn't.
Code: Select all
#TEST_A=1<<0
#TEST_B=1<<1
Macro HasTheseFlags(f)
& f = f
EndMacro
a = #TEST_A
If a HasTheseFlags(#TEST_A|#TEST_B)
Debug "Both flags are set"
EndIf
You have to use brackets:
Code: Select all
Macro HasTheseFlags(f)
& (f) = (f)
EndMacro
BarryG
Addict
Posts: 3292 Joined: Thu Apr 18, 2019 8:17 am
Post
by BarryG » Sun Oct 13, 2019 8:58 am
Thank you, STARGÅTE. Post corrected.