RosettaCodeData/Task/Integer-overflow/Nim/integer-overflow-3.nim

53 lines
2.2 KiB
Nim
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

echo "For 32 bits signed integers with overflow check suppressed:"
{.push overflowChecks: off.}
var a: int32
a = -(-2147483647i32 - 1'i32)
echo " -(-2147483647-1) gives ", a # -2147483648.
a = 2000000000i32 + 2000000000i32
echo " 2000000000 + 2000000000 gives ", a # -294967296.
a = -2147483647i32 - 2147483647i32
echo " -2147483647 - 2147483647 gives ", a # 2.
a = 46341i32 * 46341i32
echo " 46341 * 46341 gives ", a # -2147479015.
a = (-2147483647i32 - 1i32) div -1i32
echo " (-2147483647-1) / -1 gives ", a # -2147483648.
{.pop.}
echo ""
echo "For 64 bits signed integers with overflow check suppressed:"
{.push overflowChecks: off.}
var b: int64
b = -(-9223372036854775807i64 - 1i64)
echo " -(-9223372036854775807-1) gives ", b # -9223372036854775808.
b = 5000000000000000000i64 + 5000000000000000000i64
echo " 5000000000000000000 + 5000000000000000000 gives ", b # -8446744073709551616.
b = -9223372036854775807i64 - 9223372036854775807i64
echo " -9223372036854775807 - 9223372036854775807 gives ", b # 2.
b = 3037000500i64 * 3037000500i64
echo " 3037000500 * 3037000500 gives ", b # -9223372036709301616.
b = (-9223372036854775807i64 - 1i64) div -1i64
echo " (-9223372036854775807-1) / -1 gives ", b # -9223372036854775808.
{.pop.}
echo ""
echo "For 32 bits unsigned integers:"
var c: uint32
echo " -4294967295 doesnt compile."
c = 3000000000u32 + 3000000000u32
echo " 3000000000 + 3000000000 gives ", c # 1705032704.
c = 2147483647u32 - 4294967295u32
echo " 2147483647 - 4294967295 gives ", c # 2147483648.
c = 65537u32 * 65537u32
echo " 65537 * 65537 gives ", c # 131073.
echo ""
echo "For 64 bits unsigned integers:"
var d: uint64
echo " -18446744073709551615 doesnt compile."
d = 10000000000000000000u64 + 10000000000000000000u64
echo " 10000000000000000000 + 10000000000000000000 gives ", d # 1553255926290448384.
d = 9223372036854775807u64 - 18446744073709551615u64
echo " 9223372036854775807 - 18446744073709551615 gives ", d # 9223372036854775808.
d = 4294967296u64 * 4294967296u64
echo " 4294967296 * 4294967296 gives ", d # 0.