Forum
-1 = 255 (solved) - Printable Version

+- Forum (https://www.boriel.com/forum)
+-- Forum: Compilers and Computer Languages (https://www.boriel.com/forum/forumdisplay.php?fid=12)
+--- Forum: ZX Basic Compiler (https://www.boriel.com/forum/forumdisplay.php?fid=11)
+---- Forum: Bug Reports (https://www.boriel.com/forum/forumdisplay.php?fid=15)
+---- Thread: -1 = 255 (solved) (/showthread.php?tid=2296)



-1 = 255 (solved) - zarsoft - 01-19-2023

Why this gives different results?
How can I force to give -1 ?

PRINT CODE("012"(1)) - CODE("012"(2)) ' gives -1
LET w$="012": PRINT CODE(w$(1))-CODE(w$(2)) ' gives 255


RE: -1 = 255 - boriel - 01-19-2023

This is a typecast / overflow problem. The CODE w$(1) is of type UByte (unsigned byte).
So if you subtract CODE w$(1) - CODE w$(2) and the result is negative, it will be overflowed. In this case, -1 is 255 in Ubyte.

In the first line, the compiler guesses this in compile time, because it's constant. In the second case, it cannot, because it's computed during runtime.

You can tell the compiler the type of the expression using CAST. In this case, you want CODE w$(1) and CODE w$(2) to be of type Byte (not Ubyte), because it's signed (that is, it can be negative).

Try this:
Code:
LET w$="012": PRINT CAST(Byte, CODE(w$(1)) - CODE(w$(2))) ' gives -1