Bit wise option code?
Blitz3D Forums/Blitz3D Programming/Bit wise option code?
| ||
I think that's what it's called. I've seen where you can do something like this. Const GLOW = 2 Const FOG = 4 Const SKY = 8 Const GROUND = 16 MakeWorld(GLOW+FOG+GROUND) Then the function can somehow figure out what options you pick. Anyone know how to code this? |
| ||
If flags and GLOW ;glow enabled EndIf If flags and FOG ;FOG enabled EndIf etc.. |
| ||
Const Glow = 2 Const Rings = 4 Const LensRef = 6 PrintOptions(Glow+Rings) Function PrintOptions(Flag) If Flag And Glow Then Print "Glow" If Flag And Rings Then Print "Ring" If Flag And LensRef Then Print "LensRef" End Function WaitKey() I tried this, it didn't seem to work. |
| ||
Nevermid, 6 had to be an 8 |
| ||
Using these bit-flags are handy for setting a set of true/false values in one integer, instead of using a variable for every true/false value you have. Basically there are 32-bits in a number and each bit can either be set to 0 (false) or 1 (true). I always use the shift left operation to set up a bunch of flags - it's easier to follow, something like this: Const kF_Glow = 1 Shl 0 Const kF_Rings = 1 Shl 1 Const kF_LensRef = 1 Shl 2 You set flags like this: Flags = kF_Glow Or kF_Rings Or kF_LensRef Or like this: Flags = Flags Or kF_Rings (you can also use + instead of 'or' if you like, but 'or' is safer because if the flag is already set it won't cause a problem. If you use + and the flag is already set it will break because it is adding to the number, so you'll get a different value) You remove flags like this: Flags = Flags And ~kF_Glow You can test if a flag is set like this: If (Flags And kF_Glow) Then do something... You can test if a flag isn't set like this: If ( (Flags And kF_Glow) = 0 ) Then do even more stuff... You can even test if a bunch of flags are set like this: CheckFlags = kF_Glow Or kF_Rings if ((Flags And CheckFlags) = CheckFlags) ) Then do stuff... hope that helps, |
| ||
Here is a further variation, maybe useful to see what happens: If (Flag And Glow) = Glow Then Print "Glow" Let's say flag is 7 and Glow is 4 "(Flag AND GLow)" is an expression that forces a calculation. It will now set those bits in the result which are true in both, in Flag AND in Glow. Flag: binary 0111 Glow: binary 0100 You see there is only one bit set in both numbers, the third bit. So the result is 0100 So (%0111 AND %0100) = %0100 or we could say: (7 and 4) = 4 If the third bit in Flag would not be set, then the result would be zero: (3 and 4)=0 or (0011 AND 0100) = 0000 because none of the bits are set in both variables. |