Bitwise operators
Monkey Forums/Monkey Code/Bitwise operators
| ||
Hi guys, I made this based on a reference here http://blog.blindgaenger.net/bitwise_operations_for_flags.html . I decided to make a monkey version and share it. This is for making encapsulated bits which serve as flags set/unset (aka Bitwise). This could be pretty useful! Class Flags Private Field bits:Int Public Method New(bits:Int) Self.bits = bits End Method Bits:Int() Property Final Return bits End Method Bits:Void(bits:Int) Property Final Self.bits = bits End Method IsSet:Bool(flag:Int) Return ( (Self.bits & (1 Shl flag)) <> 0) End Method Set:Void(flag:Int) Self.bits = (Self.bits | (1 Shl flag)) End Method UnSet:Void(flag:Int) Self.bits = (Self.bits & ~ (1 Shl flag)) End Method Toggle:Void(flag:Int) Self.bits = (Self.bits ~ (1 Shl flag)) End End Usage: Const testA:Int = 1 ' 001 Const testB:Int = 2 ' 010 Const testC:Int = 4 ' 100 Const testD:Int = 8 ' 111 Local f:Flags = New Flags(0) f.Set(testB) If f.IsSet(testB) Then Print("Yes! Test B is SET!") f.UnSet(testB) If Not f.IsSet(testB) Then Print("No! Test B is not SET anymore!") f.Toggle(testB) If f.IsSet(testB) Then Print("Yes! Test B is SET AGAIN!") f.Toggle(testB) If Not f.IsSet(testB) Then Print("No! Test B is not SET anymore!") f.Set(testB | testC) If f.IsSet(testB | testC) Then Print("Yes! Test B and C is SET!") Enjoy! Thanks! |
| ||
Good stuff, man. |
| ||
There are some important mistakes here ! 1 = 0001 2 = 0010 4 = 0100 8 = 1000 not 111 (7) Your consts could be 1,2,3,4 because they are bit position in your functions (shl) You can't OR testb and testc as they were shifted bits, in your example you are testing only bit 6 ! |