Code archives/Algorithms/Bit Flags
This code has been declared by its author to be Public Domain code.
Download source code
| |||||
Bit flags are can be used to set parameters for a function. The value that is inputed as a parameter when calling the function is an integer, which is the sum of all the bits of parameters you want. For example: In the B+ function create window, there are many different style flags you can have. You pick which styles you want, and add up there bit values. This is the integer that is used as the flag. The default is 15, which would mean the window has a title bar, is resizable, has a menu, and has a status bar. This is useful for many things, so have fun with it! | |||||
Repeat Print flag=Int(Input$("Flag:>")) bit=Int(Input$("Bit:>")) Select bitflag(flag,bit) Case 0 Print "Bit "+bit+" has not been found in flag "+flag+"." Case 1 Print "Bit "+bit+" has been found in flag "+flag+"." End Select Forever Function bitflag(flag,bit) p=0 Repeat If 2^p>11 Then Exit p:+1 Forever p:-1 For i=p To 0 Step -1 If flag-(2^i)>=0 Then flag:-(2^i) If 2^i=bit Then Return 1 End If Next Return 0 End Function |
Comments
| ||
There is far more simple:Function bitflag(flag,bit) Return (flag Shr bit) And 1 End FunctionNote: in this version 'bit' starts at 0, not 1 (if you want it 1 base just do "Return (flag Shr (bit-1)) And 1") |
| ||
Oh, huh... and i spent and hour trying to figure this one out... |
| ||
It would be this:Function BitFlag(flag,bit) Return (flag & bit)=bit End Function Unfortunatly 'And' is only a logical opperater, not a bitwise opperator. So you have to use the & symbol. |
| ||
A working Example.;flags (multiple of 2) fullbright=1 vertexcolors=2 flatshaded=4 disablefog=8 disablebackfaceculling=16 forcealphablending=32 ;assignment fx=fullbright+vertexcolors+disablefog Print("fx="+fx+":") ;evaluate; use '/' and If's only. If fx/fullbright And 1 Print("fullbright") ;do stuff If fx/vertexcolors And 1 Print("vertexcolors") If fx/flatshaded And 1 Print("flatshaded") If fx/disablefog And 1 Print("disablefog") If fx/disablebackfaceculling And 1 Print("disablebackfaceculling") If fx/forcealphablending And 1 Print("forcealphablending") |
Code Archives Forum