Integer overflow: Difference between revisions

Updated Kotlin example since Kotlin has unsigned types.
m (syntax highlighting fixup automation)
(Updated Kotlin example since Kotlin has unsigned types.)
Line 1,625:
A Kotlin program does <b>not</b> recognize a signed integer overflow and the program <b>continues with wrong results</b>.
 
<syntaxhighlight lang="scalakotlin">// version 1.0.5-2
 
/* Kotlin (like Java) does not have unsigned integer types but we can simulate
what would happen if we did have an unsigned 32 bit integer type using this extension function */
fun Long.toUInt(): Long = this and 0xffffffffL
 
// The Kotlin compiler can detect expressions of signed constant integers that will overflow.
// It cannot detect unsigned integer overflow, however.
@Suppress("INTEGER_OVERFLOW")
fun main(args: Array<String>) {
// The following 'signed' computations all produce compiler warnings that they will lead to an overflow
// which have been ignored
println("*** Signed 32 bit integers ***\n")
println(-(-2147483647 - 1))
Line 1,647 ⟶ 1,643:
println(3037000500 * 3037000500)
println((-9223372036854775807 - 1) / -1)
// Simulated unsigned computations, no overflow warnings as we're using the Long type
println("\n*** Unsigned 32 bit integers ***\n")
// println(-4294967295U) // this is a compiler error since unsigned integers have no negation operator
println((-4294967295L).toUInt())
// println((3000000000L.toUInt(0U - 4294967295U) +// 3000000000L.toUInt()).toUInt())this works
println((2147483647L - 4294967295L4294967295).toUInt()). // converting from the signed Int type also produces the overflow; this is intended behavior of toUInt())
println((65537L3000000000U *+ 65537L).toUInt()3000000000U)
println(2147483647U - 4294967295U)
println(65537U * 65537U)
println("\n*** Unsigned 64 bit integers ***\n")
println(0U - 18446744073709551615U) // we cannot convert from a signed type here (since none big enough exists) and have to use subtraction
println(10000000000000000000U + 10000000000000000000U)
println(9223372036854775807U - 18446744073709551615U)
println(4294967296U * 4294967296U)
}</syntaxhighlight>
 
Line 1,679 ⟶ 1,681:
2147483648
131073
 
*** Unsigned 64 bit integers ***
 
1
1553255926290448384
9223372036854775808
0
</pre>
 
32

edits