最新动态

工业物联网通讯专家!
认真做好每一件事,设计简单、可靠、价格合理的产品!

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

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

在利用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类型进行移位操作。


上一篇: 有人科技新上架两款网络转串口模块产品
下一篇: 应用笔记一:将串口服务器联入外网

发表评论