您好,欢迎访问心蓝数据!    请登录  免费注册
技术文档 |  帮助文档 |  常用下载 |  新闻动态
分类 目标
当前位置: 文档 -> 技术文档  

VB程序中实现字节移位操作

加入时间: 2004/12/20 22:17:29


(李湘江 2001年04月29日 11:34)

在利用VB系统开发数据采集或工业控制软件,或对文件进行低级操作时,常需要对字节进行移位操作,但VB系统中没有提供字节移位操作的指令和函数,只提供了And(与)、Or(或)、Xor(异或)、Equ(同或)、Not(非)等几个逻辑运算指令。笔者在用VB系统开发工业控制软件的过程中,就遇到了这个问题,于是利用VB中已有的逻辑运算指令,模拟汇编语言的字节移位指令,编制了七个字节移位函数:逻辑左移、逻辑右移、算术右移、循环左移、循环右移、进位循环左移和进位循环右移。

在汇编语言指令中,逻辑左移的功能相当于乘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类型进行移位操作。

上一篇: Windows消息
下一篇: 精妙SQL语句
关于我们   联系我们   法律声明   如何付款  
版权所有© 2003-2022 心蓝数据  ICP备案: 粤ICP备05016924号