vb中的溢出

来源:百度知道 编辑:UC知道 时间:2024/06/06 03:13:27
Dim TxFrame(37) As byte
TxFrame(0) = &HC1
TxFrame(1) = &H33
TxFrame(2) = &HF1
TxFrame(3) = &H23
TxFrame(4) = 0
TxFrame(5) = &H33
TxFrame(6) = &H33
TxFrame(7) = &H1

TxFrame(8) = (TxFrame(0) + TxFrame(1) + TxFrame(2) + TxFrame(3) + TxFrame(4) + TxFrame(5) + TxFrame(6) + TxFrame(7)) And &HFF
为什么会溢出啊?我把 Dim TxFrame(37) As Integer 试了下TxFrame(8)=6F,感觉不应该溢出啊,谢谢大家~~
谢谢,我觉得pengzi121说的对,但是设中间变量好像也解决不了这个问题吧,只有把Dim TxFrame(37) As byte 改为 Dim TxFrame(37) As Integer 才不溢出,就是说不能定义为byte么这里?

你这样做是要溢出啊!
TxFrame(8) = (TxFrame(0) + TxFrame(1) + TxFrame(2) + TxFrame(3) + TxFrame(4) + TxFrame(5) + TxFrame(6) + TxFrame(7)) And &HFF
的计算过程是:TxFrame(0)=TxFrame(0) + TxFrame(1),这样算几次肯定会溢出的,建议你另外定义一个Integer变量做中间变量。

Dim temp As Integer
TxFrame(0) = &HC1
TxFrame(1) = &H33
TxFrame(2) = &HF1
TxFrame(3) = &H23
TxFrame(4) = 0
TxFrame(5) = &H33
TxFrame(6) = &H33
TxFrame(7) = &H1

temp = (TxFrame(0) + TxFrame(1) + TxFrame(2) + TxFrame(3) + TxFrame(4) + TxFrame(5) + TxFrame(6) + TxFrame(7)) And &HFF
TxFrame(8)=temp

不要定义为As Integer ,改为As long.