Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
-1 = 255 (solved)
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
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:
LET w$="012": PRINT CAST(Byte, CODE(w$(1)) - CODE(w$(2))) ' gives -1

Forum Jump:

Users browsing this thread: 1 Guest(s)