Test for an integer overflow

634 views
Skip to first unread message

JohnGB

unread,
Aug 28, 2014, 8:12:14 AM8/28/14
to golan...@googlegroups.com
Firstly, I realise that the spec allows integer overflows, and I'm not suggesting that should change.  

However I need to check to see if an overflow has occurred in some code, but I'm not sure how to do this.

So given a (simplified) function signature of  func Add(x, y int64) int64 , what would be the best way to check whether an overflow has occurred?

JohnGB

unread,
Aug 28, 2014, 8:13:31 AM8/28/14
to golan...@googlegroups.com
Typo by me.  I meant a function signature of:
func Multiply(x, y int64) int64

James Wendel

unread,
Aug 28, 2014, 8:46:53 AM8/28/14
to golan...@googlegroups.com

Rob Pike

unread,
Aug 28, 2014, 10:05:31 AM8/28/14
to James Wendel, golan...@googlegroups.com
There's likely better code than this, but I've tested this version
thoroughly and it's straightfoward.

func mulOverflows(a, b uint64) bool {
if a <= 1 || b <= 1 {
return false
}
c := a * b
return c/b != a
}

const mostNegative = -(mostPositive + 1)
const mostPositive = 1<<63 - 1

func signedMulOverflows(a, b int64) bool {
if a == 0 || b == 0 || a == 1 || b == 1 {
return false
}
if a == mostNegative || b == mostNegative {
return true
}
c := a * b
return c/b != a
}

John Beckett

unread,
Aug 28, 2014, 10:50:33 AM8/28/14
to Rob Pike, James Wendel, golan...@googlegroups.com
@Rob: That's an elegant way of solving the problem, thanks.

@James: Being lazy, I understood Rob's code better than the StackOverflow answer, so I'll go with that.  But thanks for the suggestion.


}

--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/h5oSN5t3Au4/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages