View Single Post
Old Apr 28th, 2008, 10:04 AM   #9
opa6x57
Hmmmm ... Is there more??
 
opa6x57's Avatar
 
Join Date: Apr 2008
Location: Post Falls, ID
Posts: 15
Rep Power: 0 opa6x57 is on a distinguished road
Re: Bitwise Operators...

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...

VB Syntax (Toggle Plain Text)
  1. Dim bitflag as byte
  2. If IsPatient_YN == "Y" Then
  3. bitflag = bitflag OR 1 ' Which sets the right-most (AKA LSB) bit to 1
  4. End If
  5. If IsActive_YN == "Y" Then
  6. bitflag = bitflag OR 64 ' Which sets this bit: x1xx xxxx
  7. End If
Then, on reading the data...
VB Syntax (Toggle Plain Text)
  1. If (bitflag AND 1) == 1 Then
  2. IsPatient_YN = "Y"
  3. Else
  4. IsPatient_YN = "N"
  5. End If
  6.  
  7. If (bitflag AND 64) == 64
  8. IsActive_YN = "Y"
  9. Else
  10. IsActive_YN = "N"
  11. 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.
__________________
Ken -
New to PFO ... but been dabbling in various versions of BASIC since highschool - circa 1973.

"Shouldn't the 'Air and Space' museum be empty?" - Dennis Miller
opa6x57 is offline   Reply With Quote