View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
Peter T Peter T is offline
external usenet poster
 
Posts: 5,600
Default Bitwise comparison question

Function bHasBit(ByVal num As Long, ByVal bit As Long) As Boolean
bHasBit = ((num And 2 ^ bit) = 2 ^ bit)
End Function

Sub test()
Dim i As Long
Dim strIn As String
Dim strOut As String
Dim sBin As String, sVal
Dim WeekBits As Long ' store somewhere else, eg Global

strIn = "NNYYYYN"
For i = 1 To Len(strIn)
WeekBits = WeekBits Or 2 ^ -((Mid(strIn, i, 1) = "Y") * i)

sBin = sBin & -((Mid(strIn, i, 1) = "Y"))
sVal = sVal & 2 ^ -((Mid(strIn, i, 1) = "Y") * i) & " "
Next

For i = 1 To 7
strOut = strOut & IIf(bHasBit(WeekBits, i), "Y", "N")
Next

MsgBox strIn & vbCr & sBin & vbCr & sVal & vbCr & strOut
End Sub

Hopefully looking at sBin and sVal above will go some way to giving an
explanation.
Note that bits are numbered from zero. So this demo takes advantage of not
bothering about filling the first bit, which it does with any false's, 2^0 =
1. The use of 'Or' instead or '+' prevents the false-1 added more than once.

See 'And' & 'Or' in help and more about bitwise comparison.

FWIW, you could store a month's worth of N/Y, 31days. BUT, the example would
need to modified to offset by -1, ie zero to 30. Also, you couldn't add any
false 2^0 as in this lazy demo (guess purists wouldn't like the use of the
minus to convert True(-1) to +1).

Regards,
Peter T



"Ian Gilmore" wrote in message
...
I have some data which presents active days like this NNYYYYN or any
combination of them. I am told I can store the value of all combinations
in a single integer. I have read that this can be acheived by using
bitwise comparison. Unfortunately, I have never used this so don't
really understand it without seeing a simple explanation. I know you
guys are the best so would appreciate an explanation and ideally some
sample code.

Many Thanks