VB程序中實(shí)現(xiàn)字節(jié)移位操作 在利用VB系統(tǒng)開(kāi)發(fā)數(shù)據(jù)采集或工業(yè)控制軟件,或?qū)ξ募M(jìn)行低級(jí)操作時(shí),常需要對(duì)字節(jié)進(jìn)行移位操作,但VB系統(tǒng)中沒(méi)有提供字節(jié)移位操作的指令和函數(shù),只提供了And(與)、Or(或)、Xor(異或)、Equ(同或)、Not(非)等幾個(gè)邏輯運(yùn)算指令。筆者在用VB系統(tǒng)開(kāi)發(fā)工業(yè)控制軟件的過(guò)程中,就遇到了這個(gè)問(wèn)題,于是利用VB中已有的邏輯運(yùn)算指令,模擬匯編語(yǔ)言的字節(jié)移位指令,編制了七個(gè)字節(jié)移位函數(shù):邏輯左移、邏輯右移、算術(shù)右移、循環(huán)左移、循環(huán)右移、進(jìn)位循環(huán)左移和進(jìn)位循環(huán)右移。
在匯編語(yǔ)言指令中,邏輯左移的功能相當(dāng)于乘2, 邏輯右移的功能相當(dāng)于除2,利用這個(gè)特性,在VB程序中用乘2和除2方法實(shí)現(xiàn)位的左移和右移,然后再用And(與)和Or(或)邏輯運(yùn)算指令,判斷移位過(guò)程中是否有進(jìn)位發(fā)生,將進(jìn)行標(biāo)志置位。
程序清單 CF是進(jìn)位標(biāo)志,采用Boolean類型邏輯變量,如果CF為T(mén)rue表示有進(jìn)位,為False則表示無(wú)進(jìn)位。
Public CF As Boolean '進(jìn)位標(biāo)志
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位是否進(jìn)位 SHL = (BD And &H7F) * 2 End Function
|
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位是否進(jìn)位 SHR = BD \ 2 End Function
|
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位是否進(jìn)位 BD = BD \ 2 '右移 SAR = BD Or Fg1 End Function
|
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位是否進(jìn)位 BD = ((BD And &H7F) * 2) Or Fg1 '帶進(jìn)位左移 Next i CF = Fg1 ROL = BD End Function
|
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位是否進(jìn)位 BD = (BD \ 2) Or Fg1 '帶進(jìn)位右移 Next i CF = Fg1 ROR = BD End Function
|
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位是否進(jìn)位 BD = ((BD And &H7F) * 2) Or Fg2 '帶進(jìn)位左移 Fg2 = Fg1 Next i CF = Fg1 RCL = BD End Function
|
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位是否進(jìn)位 BD = (BD \ 2) Or Fg2 '帶進(jìn)位右移 Fg2 = Fg1 Next i CF = Fg1 RCR = BD End Function
|
結(jié)束語(yǔ) 以上七個(gè)字節(jié)移位操作函數(shù)的功能和用法同宏匯編語(yǔ)言的移位操作指令基本相同,不過(guò)只對(duì)單字節(jié)進(jìn)行操作,但上述程序稍加改動(dòng)后,就可對(duì)雙字節(jié)Integer類型和四字節(jié)Long類型進(jìn)行移位操作。
|