https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Ruckus

08/08/2020, 8:50 PM
What would be the most "correct" way to add two `UByte`s together without overflow (e.g.
0xA3u + 0x91u
becomes
0xFFu
)? And the same for subtraction (e.g.
0x34u - 0x51u
becomes
0x00u
).
d

diesieben07

08/08/2020, 8:52 PM
(a.toUInt() + b.toUInt()).coerceIn(0x00u, 0xFFu).toUByte()
r

Ruckus

08/08/2020, 8:54 PM
And for subtraction would you convert to
Int
to handle negatives?
d

diesieben07

08/08/2020, 8:54 PM
Ah, missed that part... yeah I guess I'd go to
Int
then, yeah
r

Ruckus

08/08/2020, 8:58 PM
Cool, thanks. That's what I'm doing, I was just wondering if there's a better way I missed.
d

diesieben07

08/08/2020, 8:59 PM
Not that I can think of anyways
👍 1
3 Views