VB程序中實現(xiàn)字節(jié)移位操作 VB程序中實現(xiàn)字節(jié)移位操作 按位左移 右移
在利用VB系統(tǒng)開發(fā)數(shù)據(jù)采集或工業(yè)控制軟件,或?qū)ξ募M行低級操作時,常需要對字節(jié)進行移位操作,但VB系統(tǒng)中沒有提供字節(jié)移位操作的指令和函數(shù),只提供了And(與)、Or(或)、Xor(異或)、Equ(同或)、Not(非)等幾個邏輯運算指令。筆者在用VB系統(tǒng)開發(fā)工業(yè)控制軟件的過程中,就遇到了這個問題,于是利用VB中已有的邏輯運算指令,模擬匯編語言的字節(jié)移位指令,編制了七個字節(jié)移位函數(shù):邏輯左移、邏輯右移、算術(shù)右移、循環(huán)左移、循環(huán)右移、進位循環(huán)左移和進位循環(huán)右移。
在匯編語言指令中,邏輯左移的功能相當于乘2, 邏輯右移的功能相當于除2,利用這個特性,在VB程序中用乘2和除2方法實現(xiàn)位的左移和右移,然后再用And(與)和Or(或)邏輯運算指令,判斷移位過程中是否有進位發(fā)生,將進行標志置位。
程序清單
CF是進位標志,采用Boolean類型邏輯變量,如果CF為True表示有進位,為False則表示無進位。
[code]
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位屏蔽左移,防止字節(jié)溢出
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.算術(shù)右移
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.循環(huán)左移
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.循環(huán)右移
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.進位循環(huán)左移
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.進位循環(huán)右移
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
[/code]
結(jié)束語
以上七個字節(jié)移位操作函數(shù)的功能和用法同宏匯編語言的移位操作指令基本相同,不過只對單字節(jié)進行操作,但上述程序稍加改動后,就可對雙字節(jié)Integer類型和四字節(jié)Long類型進行移位操作。