在汇编语言指令中,逻辑左移的功能相当于乘2, 逻辑右移的功能相当于除2,利用这个特性,在VB程序中用乘2和除2方法实现位的左移和右移,然后再用And(与)和Or(或)逻辑运算指令,判断移位过程中是否有进位发生,将进行标志置位。
程序清单
CF是进位标志,采用Boolean类型逻辑变量,如果CF为True表示有进位,为False则表示无进位。
Public CF As Boolean '进位标志
'1.逻辑左移
Public Function SHL(OPR As Byte, n As Integer) As Byte
Dim BD As Byte
Dim I As Integer
BD = OPR
For i = 1 To n - 1
BD = (BD And &H7F) * 2 '将D7位屏蔽左移,防止字节溢出
Next i
CF = BD And &H80 '判断D7位是否进位
SHL = (BD And &H7F) * 2
End Function
'2.逻辑右移
Public Function SHR(OPR As Byte, n As Integer) As Byte
Dim BD As Byte
Dim I As Integer
BD = OPR
For i = 1 To n - 1
BD = BD \ 2 '右移
Next i
CF = BD And 1 '判断D0位是否进位
SHR = BD \ 2
End Function
'3.算术右移
Public Function SAR(OPR As Byte, n As Integer) As Byte
Dim BD As Byte
Dim I As Integer
Dim Fg1 As Byte
BD = OPR
Fg1 = BD And &H80
For i = 1 To n - 1
BD = BD \ 2 '右移
Next i
CF = BD And 1 '判断D0位是否进位
BD = BD \ 2 '右移
SAR = BD Or Fg1
End Function
'4.循环左移
Public Function ROL(OPR As Byte, n As Integer) As Byte
Dim BD As Byte
Dim I As Integer
Dim Fg1 As Byte
BD = OPR
For i = 1 To n
Fg1 = (BD And &H80) \ 128 '判断D7位是否进位
BD = ((BD And &H7F) * 2) Or Fg1 '带进位左移
Next i
CF = Fg1
ROL = BD
End Function
'5.循环右移
Public Function ROR(OPR As Byte, n As Integer) As Byte
Dim BD As Byte
Dim I As Integer
Dim Fg1 As Byte
Dim Fg2 As Byte
BD = OPR
For i = 1 To n
Fg1 = (BD And 1) * 128 '判断D0位是否进位
BD = (BD \ 2) Or Fg1 '带进位右移
Next i
CF = Fg1
ROR = BD
End Function
'6.进位循环左移
Public Function RCL(OPR As Byte, n As Integer) As Byte
Dim BD As Byte
Dim I As Integer
Dim Fg1 As Byte
Dim Fg2 As Byte
BD = OPR
Fg2 = CF And 1
For i = 1 To n
Fg1 = (BD And &H80) \ 128 '判断D7位是否进位
BD = ((BD And &H7F) * 2) Or Fg2 '带进位左移
Fg2 = Fg1
Next i
CF = Fg1
RCL = BD
End Function
'7.进位循环右移
Public Function RCR(OPR As Byte, n As Integer) As Byte
Dim BD As Byte
Dim I As Integer
Dim Fg1 As Byte
Dim Fg2 As Byte
BD = OPR
Fg2 = CF And 128
For i = 1 To n
Fg1 = (BD And 1) * 128 '判断D0位是否进位
BD = (BD \ 2) Or Fg2 '带进位右移
Fg2 = Fg1
Next i
CF = Fg1
RCR = BD
End Function
结束语
以上七个字节移位操作函数的功能和用法同宏汇编语言的移位操作指令基本相同,不过只对单字节进行操作,但上述程序稍加改动后,就可对双字节Integer类型和四字节Long类型进行移位操作。