My job often requires that I take the data created by someone else's program - and extract the parts I need into something we can use.
When extracting useful data from various binary files - I often have to use the AND operator ... A common use of bit-wise math is encoding several flags into a single byte.
Suppose the program needed to store these 8 YES/NO flags:
IsPatient_YN
IsDoctor_YN
IsHealthPlan_YN
HasID_YN
HasPhone_YN
HasFax_YN
IsActive_YN
IsDeleted_YN
This could be stored as a series of single-byte entries - each entry using the single character "Y" or "N".
However, using bit-wise operators - the program could store all 8 of these flags in a single byte...
Dim bitflag as byte
If IsPatient_YN == "Y" Then
bitflag = bitflag OR 1 ' Which sets the right-most (AKA LSB) bit to 1
End If
If IsActive_YN == "Y" Then
bitflag = bitflag OR 64 ' Which sets this bit: x1xx xxxx
End If
Then, on reading the data...
If (bitflag AND 1) == 1 Then
IsPatient_YN = "Y"
Else
IsPatient_YN = "N"
End If
If (bitflag AND 64) == 64
IsActive_YN = "Y"
Else
IsActive_YN = "N"
End If
So, rather than storing the characters "Y" or "N" using 8 bytes - you can store this same information in a single byte.
(This is a small savings - and in these days with large storage devices - some would argue that the space saved is not worth the extra work. But if you're writing a program that deals with millions of individual records - this can be a significant savings...)
A similar algorithm is (was) used in the original DOS directory entries ... the 'archive-bit' was set on a directory entry in certain circumstances. The other bits in that byte controlled the 'read-only' flag - the 'system-file' flag, etc.