VB.NET中怎样实现位运算

来源:互联网 发布:考勤系统怎么导出数据 编辑:程序博客网 时间:2024/05/17 03:54

这几天一直在边学习边写一个上位机PC应用程序,用来接收串口收到的数据,并已要求的格式实时保存,再将数据以实时曲线的方式绘制出来。下位机是和ADI的ads21469通信,数据时1K Hz/s的采样率,即每秒采1024个点。以整数型式传过来,每个整数32bit表示。由于DSP那边只能是char型发送数据,所以我们把一个整数拆成了4个字节发送。这样就涉及到DSP那边的位移运算。先发高位:

int SendData[1024];

int i=0;

int tmpSend = 0;

int* sendPtr = NULL;

//Get real time sendData here

int sendFuntion(int * argSendData, int argSendNum)

{

for(i=0;i<argSendNum;++i)

{

tmpSend = SendData[i];

sendPtr[i*4] = (tmpSend >> 24) & 0xFF;

sendPtr[i*4+1] = (tmpSend >> 16) & 0xFF;

sendPtr[i*4+2] = (tmpSend >> 8) & 0xFF;

sendPtr[i*4+3] = tmpSend  & 0xFF;

}

//send data through uart, realize by DMA module

}

......

由于VB.NET 没有位移运算,故数学方式还原,即就是DSP左移24位,VB.NET中则乘以2^24还原,DSP左移16位则VB.NET中乘以2^16还原。。。。可是后面调试时就发现一个问题:当DSP端采集的数据为负值时,例如-398(FF FF FE 72)。到PC端接受时,就为255*2^24+255*2^16+254*2^8+114*2^0 = 4294966898, 已超出VB.NET中32位interger类型所能表示的最大范围:(-2147483648~~2147483647),程序运行时就会报错!我只能以long型来接受来自DSP端的数据,但是这样收到的就是个正数,刚开始尝试用转为16进制再通过求补码来获得,最后没能力实现,或者这样的想法在VB中可能行不通。

到最后其实发现真正问题的解决方法很简单,还是自己对VB不熟悉的缘故:

bitarray类BitVector32类实现,VB中提供了很方便的库函数,这很类似于C++中的bitset类型操作(需要包含<bitset>文件)。BitVector32对象可以存储一组占用32个连续位的小整数,因此对位编码字段非常有用,尤其在和硬件设备传递数据时!(大家可以参考《Visuanl Basic 2005 技术内幕》,(意)Francesco Balena 著,贾洪峰 译,清华大学出版社)

VB实现大致如下:

Imports System.Collections.Specialized

...


Dim bvData as BitVector32

Dim sec1 As BitVector32.Section = BitVector32.CreateSection(255)

Dim sec2 As BitVector32.Section = BitVector32.CreateSection(255,sec1)

Dim sec3 As BitVector32.Section = BitVector32.CreateSection(255,sec2)

Dim sec4 As BitVector32.Section = BitVector32.CreateSection(255,sec3)


Dim Buf(4096) as Byte 'receive byte size matched with DSP send data: 1024*4Byte

Dim recCount as Integer

Dim Data(1024) as long

....

For recCount = 0 To 1023

bvData(sec4) = buf(recByte*4)

bvData(sec3) = buf(recByte*4+1)

bvData(sec2) = buf(recByte*4+2)

bvData(sec1) = buf(recByte*4+3)


Data(recCount) = bvData.Data '这样数据肯定是-398

Next

....

0 0
原创粉丝点击