Monday, 4 February 2013

Basic Bitwise made easy for VB.NET

If you are searching BitWise in VB.Net on the web, you will come across a billion references telling you every little detail about the math in how they work. I won’t do that….

All I will give you is the synopsis:

'Define your flags: (FlagsAttribute warns the compiler)
<Flags()> _
Enum SettingFlags AS Integer 
    SettingA = 1
    SettingB = 2
    SettingC = 4
    SettingD = 8
    SettingE = 16
    SettingF = 32
    SettingG = 64
    SettingH = 128
    SettingI = 256
    SettingJ = 512
    SettingK = 1024
    SettingL = 2048
    SettingM = 4096
    SettingN = 8192
    SettingO = 16384
    SettingP = 32728 
    CominationAtoD = SettingA or SettingB or SettingC or SettingD ' = 15
End Enum
'Define your settings (all flags are off)
Dim YourSettings AS SettingFlags = 0
'Turn some flags on (using OR):
YourSettings = YourSettings OR SettingsFlags.SettingE
YourSettings = YourSettings OR SettingsFlags.CombinationAtoD
YourSettings = YourSettings OR 32
'Now YourSetting=63 meaning SettingA,B,C,D,E,F are all "on"
'Turning a flag off (using AND NOT)
YourSettings = YourSettings AND NOT SettingsFlags.SettingB
'Now YourSettings=61 meaning SettingsA,C,D,E,F are all "on"
'Toggle a flag (using XOR)
YourSettings = YourSettings XOR SettingsFlags.SettingsG
YourSettings = YourSettings XOR SettingsFlags.CombinationAtoD
'Now YourSettings=114 meaning SettingsB,E,F,G are "on" 
'Determine if a flag is on (using AND MASK = MASK)
IF (YourSettings AND SettingsFlags.SettingsB) = SettingsFlags.SettingsB THEN
    'In this case true, because SettingsB is "on"

In the end, all you have is a integer variable definition (make it ulong if you need more bits) that can act as a grouping of Boolean variables via the binary representation of the integer, where 1 is true, and 0 is false. I avoid demonstrating “Bit Shifting” because different programming languages handle it differently.

Now the above is self-explanatory, and my comments give examples and explanations. If you want more information or education you can sift through a million references I found on the subject below.


Other than that, copy and paste my code. And use it. It’s useful for calling functions, combining similar variables/settings, or simplifying your database.

Feel free to leave your comments or suggestions!



Page Hits