Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Mixing variable types in a numerical calculation
(01-05-2021, 06:25 PM)patters Wrote: Since castleIntactAttr is the sum of four 8bit numbers it does go higher than 255, which is where I ran into the problem. The PEEK (n+4), PEEK (n+5) etc. are colour and brightness values from a lookup table of DEFB entries, since the castle sprites need different colours and brightness values depending on the landscape colours. The castle hasn't been drawn at this point so the ATTR function isn't useful here. I invoke this as part of a sub to update the castle graphics when the landscape or time of day changes, and so this is a good place to recalculate the castleIntactAttr after the graphics have changed.

To understand this a bit better:

castleIntactAttr=(64*CAST(UINTEGER, PEEK (n+4))+8*skyCol+PEEK (n+5)+64*PEEK (n+6)+8*skyCol+PEEK (n+7))*2

                                   always<255           always<255    always<255       (they are attribute bits)
        UINTEGER=    UINTEGER    +  UBYTE      +UBYTE+    UBYTE    +   UBYTE     +UBYTE

At this last point will the compiler be intelligent enough to add all of these UBYTES to the UINTEGER left to right and hence not overflow?
Yes, it should work. In such case, don't use UByte variables and simplify the above expression. If the expression is that complicated, using UByte you're not gaining anything. On the contrary, you're wasting memory and speed, because conversion takes time and generates more code.

Also you can use a macro to simplify such expression:

#define UPEEK(x)  CAST(Uinteger, Peek(x))
castleIntactAttr=(64* UPEEK(n+4)+8*skyCol+PEEK (n+5)+64*UPEEK (n+6)+8*skyCol+PEEK (n+7))*2

Finally, if you want to compare 4 bytes, for a change it's better to store them in a Ulong (32 bits) integer. You can PEEK not only bytes, but also integers, longs and floats with PEEK (<type>, <address>):
DIM castleIntactAttr as ULong

castleIntactAttr = PEEK(ULong, n + 4)

This is definitely *much* faster and cleaner.

Messages In This Thread
RE: Mixing variable types in a numerical calculation - by boriel - 01-06-2021, 08:55 AM

Forum Jump:

Users browsing this thread: 1 Guest(s)