overflow, underflow, carry, zero etc in integer ops

164 views
Skip to first unread message

xiio...@gmail.com

unread,
Jul 12, 2016, 10:19:10 AM7/12/16
to golang-nuts
Is there an 'easy' way to get this cheap from integer ops

eg to check for carry on addition of two uint8s I need to do something like


(best I can think of)

I really wanted something like

var a,b uint8 = 200,100
x,error : = a+b

gives x=44, with error.carry = true and error.overflow=true .. this suggestion wouldn't fit with multiple value assignments eg a,b = a+b,a-b

my current method is very cludgy, and I doubt (?) it compiles to anything like the minimal assembler equivalent. 

Thinking about a builtin math error variable (different from the Error package) - functioning as struct{overflow,carry,negative,underflow etc bool}


This isn't going to happen or be fixed soon.. Is there an easier way, in terms of both efficiency (ie what it compiles to) and appearance (ie "do what I say" quality), ..  or any other thoughts ??

Uli Kunitz

unread,
Jul 12, 2016, 12:40:17 PM7/12/16
to golang-nuts, xiio...@gmail.com
You need compare the result with one summand to detect overflow.

See here: https://play.golang.org/p/3Uh0eFSbQW

Programming languages usually don't provide access to machine level flags, because they support combining multiple operations in one expression. For example what should the carry flag represent in an expression y = a + b + c. There are several strategies to deal with this shortcoming one approach is to calculate with 63-bit words and check use the highest bit as carry or do additional operations as you are doing.

I recommend to look into Harry S. Warren's book "Hacker's Delight" which contains numerous examples how to deal with such issues in a higher level language. Here is the web page for the book: http://www.hackersdelight.org/

xiio...@gmail.com

unread,
Jul 13, 2016, 12:12:32 PM7/13/16
to golang-nuts, xiio...@gmail.com
ok thanks. I'm able to move on/forward now :) 
Reply all
Reply to author
Forward
0 new messages