Force signed Bytes wuith Peek/Poke

Blitz3D Forums/Blitz3D Beginners Area/Force signed Bytes wuith Peek/Poke

_PJ_(Posted 2011) [#1]
Hey folks, does anyone know a means of 'forcing' the use of 'Signed' bytes when using Peek/PokeByte commands?

The reason for asking is that I seem to getting some unexpected values when I Peek some results back, these results are typically 200+ and ought to be negative and smaller in magnitude than 50.
The only explanations I can think of for this occurrence, is that Peek does not result signed bytes, or that the memory I am accessing is already used. I've re-run the program a few times etc. restarted PC even so I doubt it's a memory issue there.


_PJ_(Posted 2011) [#2]
hrm... Sorry! never mind!

I really only need to worry about small magnitude values (Abs(n) < 90 ) or so, which means that I can just add in a quick check:

n=PeekByte(Bank)
If (n>127) Then n=(n-255)


Yet again, I'm cursed by late-night-coder fatigue and missed the obvious! :D


Yasha(Posted 2011) [#3]
The simple answer is that yes, bytes and shorts do not preserve sign. The upper three bytes of the value passed to PokeByte will be ignored.

The slightly longer answer is that there is no difference between signed and unsigned numbers, only the interpretation of them in certain special contexts. In "two's complement", the negative numbers are simply represented by the same bit patterns as the upper half of the unsigned range (which is why -1 has the bit pattern of the highest unsigned value).

Anyway, what this means is that if you want signed bytes, all you have to do is detect whether the byte value falls in the upper half of the "Byte" range, and if so, wrap it around. There are a couple of ways to do this:

If bVal > 127 Then bVal = bVal - 256
...or...
If bVal And 128 Then bVal = bVal Or $FFFFFF00


...etc.

EDIT: eh, ninja'd. But note that you should subtract 256, not 255.

Last edited 2011


_PJ_(Posted 2011) [#4]
:)

Thanks Yasha, and yeah, as soon as I first ran my code with the change I picked up on the error of using 255, byut thanks for noticing!