以下两个程序实现相同功能,将长度为4的字节数组转化成长整形变量。这也是一个常用的功能。
方法一:最常规的方法,按权累加,
Public Sub test1()
Dim t1 As Single
Dim t2 As Single
Dim i As Long
Dim a(3) As Byte
Dim b As Long
a(0) = 101
a(1) = 123
a(2) = 232
a(3) = 78
t1 = Timer
For i = 1 To 10000000
b = ((CLng(a(3)) * 256 + a(2)) * 256 + a(1)) * 256 + a(0)
Next i
t2 = Timer
Debug.Print "单次耗时: " & (t2 - t1) / 10 & "微妙"
Debug.Print "b = " & b
End Sub
计时结果:
b = 1323858789
单次耗时: .4289063微妙
方法二:采用API复制数据,直接合并四个字节变量为一个长整形变量。
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal pDest As Any, ByVal pSrc As Any, ByVal ByteLen As Long)
Public Sub test2()
Dim t1 As Single
Dim t2 As Single
Dim i As Long
Dim a(3) As Byte
Dim b As Long
a(0) = 101
a(1) = 123
a(2) = 232
a(3) = 78
t1 = Timer
For i = 1 To 10000000
CopyMemory VarPtr(b), VarPtr(a(0)), 4
Next i
t2 = Timer
Debug.Print "单次耗时: " & (t2 - t1) / 10 & "微妙"
Debug.Print "b = " & b
End Sub
计时结果:
b = 1323858789
单次耗时: .2820312微妙
[此贴子已经被作者于2005-9-21 22:58:05编辑过]
|