Read flag?

BlitzMax Forums/BlitzMax Beginners Area/Read flag?

BLaBZ(Posted 2010) [#1]
How are flags read?

I'd imagine you could do it bitwise somehow but is that ideal?


Czar Flavius(Posted 2010) [#2]
& the value which stores the flag, with the number of the flag I believe.

If the flag is 4, that's 00001000

If the value is 00101100

00101100 &
00001000 =
00001000

which is non-zero, hence the flag is set.


TaskMaster(Posted 2010) [#3]
4 is 00000100.


TomToad(Posted 2010) [#4]
The most common way is to use Const to define a name for each bit position, then use that for setting and reading flags. Something like this:



dawlane(Posted 2010) [#5]
As TomToad says it's best to use constants to define what each bit does. I tend to use Hexadecimal numbers as it's more readable and less typing.

EDIT: Note that in the example I've used a byte just to make it a little more easier to follow. For speed its better to use the cpu's word size (four bytes for a 32bit CPU) this is because of how a CPU accesses memory.


Czar Flavius(Posted 2010) [#6]
My apologies!

Here is a quick way to set up the flags...
Const flag1 = 1 Shl 0 '1
Const flag2 = 1 Shl 1 '2
Const flag3 = 1 Shl 2 '4
Const flag4 = 1 Shl 3 '8
Const flag5 = 1 Shl 4 '16
Const flag6 = 1 Shl 5 '32
Const flag7 = 1 Shl 6 '64


Never use Bytes unless you have a specific need to. Ints are faster than bytes.


GfK(Posted 2010) [#7]
Here is a quick way to set up the flags...
Const flag1 = 1 Shl 0 '1
Const flag2 = 1 Shl 1 '2
Const flag3 = 1 Shl 2 '4
Const flag4 = 1 Shl 3 '8
Const flag5 = 1 Shl 4 '16
Const flag6 = 1 Shl 5 '32
Const flag7 = 1 Shl 6 '64
Eh??

Why not Const flag7 = 64 etc?? What's with all the unnecessary bitshifting?


Czar Flavius(Posted 2010) [#8]
You can copy and paste and just change one number, and it goes up by 1 so it's easy to remember? It's just a suggestion not a recommendation. As they're consts the bitshifting is done at compile time, so there is no performance loss.


GfK(Posted 2010) [#9]
You can copy and paste and just change one number, and it goes up by 1 so it's easy to remember?
Pffffft!! :D


Czar Flavius(Posted 2010) [#10]
For the ultimately lazy:
Global myflag1:Int = autoflag("myflag")
Global myflag2:Int = autoflag("myflag")
Global myflag3:Int = autoflag("myflag")
Global myflag4:Int = autoflag("myflag")
Global myflag5:Int = autoflag("myflag")
Global myflag6:Int = autoflag("myflag")

Function autoflag:Int(id:String)
    Global flagmap:TMap = New TMap
    If flagmap.Contains(id)
        Local flag:Int = Int(String(flagmap.ValueForKey(id)))
        flagmap.Insert(id, String(flag+1))
        Return 1 Shl flag
    Else
        flagmap.Insert(id, String(0))
        Return autoflag(id)
    End If
End Function

Note: do not use this.