Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
UBYTE/FOR loop issue?
#4
LTee Wrote:Aha, I see - thanks for that. The thought had occurred to me that perhaps this was unavoidable, but it's nice to know for sure. Thanks for the info and the pointers!

While we're here and talking about types, could anyone tell me if there's a more elegant way to do this?

I have three UBYTES with values. I want to add them up, divide by three to get an average, and put the result into another UBYTE. However, I can't just do the maths with the UBYTES because the addition takes the value > 255 and information is lost.

I came up with this solution:
[...] (Code)
... but it seems kind of messy. Is there a way to do that better?

I suppose the easiest way would be to store the three values as UINTEGERs to begin with and then cast to UBYTE at last minute, after the calculation?
It's this way, but you can use CAST(Uninteger...) dynamically:
Code:
DIM x, y, z, q as UBYTE

x = 57
y = 127
z = 204

q = (cast(Uinteger, x) + y + z) / 3
print q
That is, CAST(Uinteger, x) => Uinteger, so remaining parts wil be converted to uinteger automatically (always converted to the bigger type). You can also use CAST explicitly on y and z, but it's redundant here. Also, when storing the result into q, the type is enforced to be uByte back again. This is also the way C (and most traditional compilers) work. It's a rather advanced way, I think :oops: so you might prefer using cast explicitly on every type conversion instead of relaying on implicit ones.
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 2 Guest(s)