To see a working example download the source code for this tutorial.
What binary is and a brief look at what we're going to do
Binary is the base two number system that computers use to store variables in the RAM / memory. The number system consists of 0's and 1's and the easiest way to explain how it fits together to form numbers is to do a worked example comparing the Base 10 number system with the Base 2.
With base ten, in primary school we learned about hundreds, tens and units. There are also thousands etc... These numbers are worked out with the formula:
10^0 = 1
10^1 = 10
10^2 = 100
Relating this to base two we find that the increments are as follows: 2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
Look familiar? They should, 2^5 = 32, which used to be how much RAM I had. :-)
When we want to work out what a binary number is in decimal, we use the calculator in the accessories program group, or if we are misfortunate enough not to have that we can work it out manually as follows:
Convert 321 from base 10 to base 2
Take the number and divide by 2, record the remainder
Num = 160 Rem = 1
Repeat process with the new number, recording the remainder once more
Num = 80 Rem = 0
Num = 40 Rem = 0
Num = 20 rem = 0
Num = 10 rem = 0
Num = 5 rem = 0
Num = 2 rem = 1
Num = 1 rem = 0
Write down the final number, and all the remainders in reverse order
This really equates to:
Which you can work out and it'll be 321.
So now what we want to do is set up all of our flags that we're going to set in increments of 2^n, as follows:
Const MONSTER_MELEE as Integer = 1 Const MONSTER_RANGED as Integer = 2 Const MONSTER_AGGRESSIVE as Integer = 4 Const MONSTER_DEFENSIVE as Integer = 8 Const MONSTER_LUCKY as Integer = 16
So what we have in effect done is assigned all the different possible flags to a different bit of the integer. Integers have 2 bytes = 16 bits.
So far, in order from top to bottom, the above constants would have values like so:
Now we are in a position to set multiple flags to a single integer!
How to use it in the code
To utilise these constants that we've set up we just have to link them together using an Or Operator.
The Or operator is a bitwise operator which means that it will combine values together by going through each bit in memory and Or'ing it with the other value. The Or Table looks like this:
0 Or 0 = 0
1 Or 0 = 1
0 Or 1 = 1
1 Or 1 = 1
So in code what we'll do is this:
Dim intBehaviour as Integer ' give us an orc! intBehaviour = MONSTER_MELEE Or MONSTER_AGGRESSIVE ' Now to test if the orc is aggressive you would code: If (intBehaviour And MONSTER_AGGRESSIVE) = MONSTER_AGGRESSIVE then 'Twas an aggressive monster End if 'Similarly you could test for any of the other conditions that way
So now you can use bit flags in your programs. I hope this Visual Basic 6 tutorial is helpfull to you. If you have any questions or comments please post them below. If you would like to see an example of this download the Visual Basic 6 source code for this tutorail.