为Access数据库添加位运算函数
最近想利用Access做数据库,开发一个系统,其中涉及到一个数据匹配的算法。这个算法我们是依靠掩码技术实现的,就类似操作系统中的权限系统中的设置。每一个权限占一个二进制位,而任意的权限相加都不会重复,所以记录用户都具有哪些权限,只需要记录一个数字即可(用户所有权限的和)。
如果想验证用户是否具有某项权限,只需要将用户具有的权限与要验证的权限作一个二进制与运算,如果得到的值〉0则表示具有权限,而=0则表示不具有权限。如:会员的权限是3,要验证会员是否具有权限1,只需要运算 3 & 1即:二进制的0000,0011 与0000,0001进行二进制逐位与,得到的结果是:0000,0001〉0所以具有此权限。
以前类似的算法,在Sql server中运行很好,因为SQL Server提供了很好的二进制运算支持,可是在Access的Jet引擎中却无法实现,只因为他不提供二进制运算操作。
后来,查阅了一些资料,原来Access/Jet中可用VBA函数在JET Sql中也同样有效。好了,解决方案有了,我自己写一个二进制操作函数不就行了?
下面就是我的代码了,呵呵:
如果想验证用户是否具有某项权限,只需要将用户具有的权限与要验证的权限作一个二进制与运算,如果得到的值〉0则表示具有权限,而=0则表示不具有权限。如:会员的权限是3,要验证会员是否具有权限1,只需要运算 3 & 1即:二进制的0000,0011 与0000,0001进行二进制逐位与,得到的结果是:0000,0001〉0所以具有此权限。
以前类似的算法,在Sql server中运行很好,因为SQL Server提供了很好的二进制运算支持,可是在Access的Jet引擎中却无法实现,只因为他不提供二进制运算操作。
后来,查阅了一些资料,原来Access/Jet中可用VBA函数在JET Sql中也同样有效。好了,解决方案有了,我自己写一个二进制操作函数不就行了?
下面就是我的代码了,呵呵:
1
2
'Binary and operate
3
Public Function BitAnd(ByVal a As Long, ByVal b As Long) As Boolean
4
If (a <= 0 Or b <= 0) Then
5
BitAnd = False
6
Exit Sub
7
End If
8
Dim b1() As Integer, b2() As Integer
9
ToBytes a, b1
10
ToBytes b, b2
11
Dim i As Integer
12
For i = 0 To 32
13
If b1(i) = b2(i) And b1(i) = 1 Then
14
BitAnd = True
15
Exit Function
16
End If
17
Next i
18
BitAnd = False
19
End Function
20
21
Private Sub ToBytes(ByVal v As Long, ByRef result() As Integer)
22
ReDim result(32) As Integer
23
Dim iLoc As Integer
24
DecToBin v, result(), iLoc
25
26
End Sub
27
28
Private Sub DecToBin(ByVal v As Long, ByRef result() As Integer, ByRef iLoc As Integer)
29
If v < 2 Then
30
result(iLoc) = v
31
Exit Sub
32
End If
33
Dim r As Integer
34
r = v Mod 2
35
result(iLoc) = r
36
iLoc = iLoc + 1
37
Dim m As Long
38
m = v \ 2
39
DecToBin m, result, iLoc
40
End Sub
41

2
'Binary and operate3
Public Function BitAnd(ByVal a As Long, ByVal b As Long) As Boolean4
If (a <= 0 Or b <= 0) Then5
BitAnd = False6
Exit Sub7
End If8
Dim b1() As Integer, b2() As Integer9
ToBytes a, b110
ToBytes b, b211
Dim i As Integer12
For i = 0 To 3213
If b1(i) = b2(i) And b1(i) = 1 Then14
BitAnd = True15
Exit Function16
End If17
Next i18
BitAnd = False19
End Function20

21
Private Sub ToBytes(ByVal v As Long, ByRef result() As Integer)22
ReDim result(32) As Integer23
Dim iLoc As Integer24
DecToBin v, result(), iLoc25
26
End Sub27

28
Private Sub DecToBin(ByVal v As Long, ByRef result() As Integer, ByRef iLoc As Integer)29
If v < 2 Then30
result(iLoc) = v31
Exit Sub32
End If33
Dim r As Integer34
r = v Mod 235
result(iLoc) = r36
iLoc = iLoc + 137
Dim m As Long38
m = v \ 239
DecToBin m, result, iLoc40
End Sub41


浙公网安备 33010602011771号