Hi Everyone!
Here's some code for bitfields. It's 100% written by me.
Code:
Private Function SetBit(ByVal Field As Byte, ByVal Bit As BitField, ByVal Value As Boolean) As Byte
'Use AND to read, and use OR to write true, use AND NOT to write false
SetBit = 0
If Value = True And (Field And Bit) <> Bit Then 'If the setting was false, and we want to set it true
Field = (Field Or Bit)
SetBit = 1
Exit Sub
ElseIf Value = False And (Field And Bit) = Bit Then 'If the setting is true, and we want to set it false
Field = (Field And Not Bit)
SetBit = 1
Exit Sub
Else
SetBit = 2 'Symbol that we didn't need to change the value
Exit Sub
End If
End Function
Private Function GetBit(ByVal Field as byte, ByVal Bit As BitField) As Boolean
GetBit = False
If (Field And Bit) = Bit Then
GetBit = True
End If
End Function
Now use an enum to hold the names and 'values' of a bit.
Code:
Enum BitField
Unused_1 = 1
Unused_2 = 2
Unused_4 = 4
Unused_8 = 8
Unused_16 = 16
Unused_32 = 32
Unused_64 = 64
Unused_128 = 128
End Enum
The names are unimportant, but the values are.
Now create a variable to hold the value of this bitfield. Feel free to make it global. If you will be only using one bitfield, you can modify the GetBit and SetBit functions to access that directly, instead of passing it as a variable.
Now when you call GetBit or SetBit, you even get to see the name of the bit you want to get/set
So what's this used for?
A bit is a on or off variable, true or false. In visual basic, two bytes (16 bits) are used to store a true or false. We can store 16 bitfield values in that ammount of space!
To expand on this code, you could add the ability to do an integer, or long's worth of bits. Just add to the Enum continuing the powers of 2, and change the data type in the functions.
Enjoy~