Allowing integers to overflow to 0


#1

I’ve come across a place where allowing a UInt8 to overflow to 0 on adding 1 is the proper behavior.

Is there something like a decorator macro to allow the overflow and not get the overflow error with adding 1 to 255::UInt8 ?


#2

Julia doesn’t trow overflow errors by default:

julia> UInt8(255) + UInt8(1)
0x00

#3

I assume you were doing,

julia> UInt8(UInt8(255) + 1)
ERROR: InexactError: trunc(UInt8, 256)
Stacktrace:
 [1] throw_inexacterror(::Symbol, ::Any, ::Int64) at ./boot.jl:567
 [2] checked_trunc_uint at ./boot.jl:597 [inlined]
 [3] toUInt8 at ./boot.jl:659 [inlined]
 [4] UInt8(::Int64) at ./boot.jl:719
 [5] top-level scope at none:0

(Or the equivalent with a typed variable/field array element). You can avoid the overflow check in the conversion (NOT the add) by using % instead. i.e.

julia> (UInt8(255) + 1) % UInt8
0x00

which could be useful in other cases but the better way to deal with + 1 in particular would be to do what @favba posted, i.e. make sure both operand have the right type to begin with.


#4

Ah the bug was in adding one not adding UInt8(1).

I did not know you could do modulus with types. Thanks.