What I mean is: If a byte has value of 255, and I add 1. It becomes 0 again. Or if I subtract 1 from a zero value it becomes 255. I have a lot of code, that treats bytes like this, and I'd rather not sift through all them lines to find occurrences of such rotations
Well, nothing ventured and all that...
Cheers Jhonny
Edit: Just a dumb example:
Sub Tester()
Dim Arr(255) As Byte
Dim BytePointer As Byte = 200
Dim value As Byte
Arr(50) = 1
For i = 0 To 5000
BytePointer = BytePointer 1
value = Arr(BytePointer)
If value = 1 Then MessageBox.Show("Found 1")
Next
end sub
As such it results in an overflow exception.
Can this work without doing:
BytePointer = (BytePointer 1) and &FF
CodePudding user response:
You didn't specify the BASIC that you use, but this answer assumes FreeBasic.
You should declare the BytePointer variable as UByte
.
The number range for Byte
is from -128 to 127 ("signed"), but for UByte
it is 0 to 255 ("unsigned") which nicely matches the array bounds.
When your code initializes the BytePointer variable with Dim BytePointer As Byte = 200
, FreeBasic already sets it at -56, and when your code increments the BytePointer variable with BytePointer = BytePointer 1
it becomes -55.
The instruction value = Arr(BytePointer)
will not address an element of your array since this index (-55) is out of bounds (0,255).
Next code works fine and has no problem with the wraparound from 255 back to 0:
Dim Arr(255) As Byte
Dim BytePointer As UByte = 251
Dim value As Byte
Dim i As Integer
For i = 0 To 255
Arr(i)=i
Next
For i = 1 To 10
value = Arr(BytePointer)
Print BytePointer, value
BytePointer = BytePointer 1
Next
CodePudding user response:
OK....
By "Removing integer overflow checks in the Advanced Compiler Options dialog", you can wrap-around bytes and integers, without overflow-errors.
But it does so for the whole project.
I can work with this...
It's a shame though, that VB does not offer variables (let's call them winteger or wbyte) that do this by default. (just my 2 cents...)