Saving DB Size/Program Memory by using the AND operator and numeric variables
This article can work with all programming languages (examples in VB for ease of understanding). If you have ever worked with a database with TONS of Yes/No (Access) or Bit (SQL Server) fields, this article can help cut down database size, for example, or memory if you use individual variables to hold True or False values.
This example applies more to database coding more than memory management, but use as you like.
Suppose you have 5 variables, all holding a Boolean value. The variables are boolIsMale, boolIsFemale, boolHasDog, boolHasCat, boolHasFish.
If you were to make this one single variable, it would be easier to process this data. What we do is declare a variable as a LONG type and set it to zero.
Declare lngPerson as Long
lngPerson = 0
Through commenting your code (so you don't forget, set representations of each of those Boolean values above to a number. This is important - the numbers have to be either a number one (1) or a power of 2 (2, 4, 8, 16, 32, et. al).
' Is male = 1
' Is female = 2
' Has cat = 4
' Has dog = 8
' Has fish = 16
To say that this particular person for example was FEMALE, and has a CAT and a DOG, you would assign the variable to the sum of those numbers.
lngPerson = 2 + 4 + 8
Now what about READING the variable? This is simple.
bool_ret_val = (longval AND test_num) = test_num
To retrieve a boolean value for the example above, use the statement to test whether this person has a DOG (the representation for dog is 8 as in the comments).
boolHasDog = (lngPerson AND 8) = 8
Since this person does not have fish (we did not add 16 to lngPerson above), this next example would return False.
boolHasFish = (lngPerson AND 16) = 16
The expression (lngPerson AND 16) would actually return 0.
For a more real-world example, if you have an SQL Server database that holds a table with a LOT of BIT fields (1's and 0's representing True and False for those still stuck using Access), you can cut down easily on the size of the database by making a numeric field and using the above example as a base for your programming. But heed this word of caution - you need a field bigger than INT if you're combining a lot of fields - Watch how quickly powers of 2 grow!
For the VB integer, the above already constitutes as an overflow. Make sure you use a LONG variable.
Please make sure to post comments if you need more help, and vote if you like!