This is the wrong list to ask such a question, but I'll answer it anyway since the answer might be of general interest.

There is a wonderful book "Hacker's Delight" by Henry S. Warren Jr.,

http://www.awprofessional.com/bookstore/product.asp? isbn=0201914654&redir=1&rl=1

In some ways it can be thought of as building on the HAKMEM memos of MIT; it has a Forward by Guy Steele. The book has a lot of fast bit-twiddling (unbelievably, "twiddling" just passed my Mac's spell-checker) algorithms for operating at the machine word level and gives the answer to your question in Chapter 1.

Assuming that overflow of signed integer arithmetic wraps (and what gcc flag do I have to set to assume this?) then here is the algorithm to multiply x and y with overflow detection.

if y = 0 then
   result = 0
else if y = -1 then
  if x = the_minimum_negative_value then
      result = overflow
  else
      result = -x
else
  let z = x * y;
     if z / y = x then
        result = z
     else
        result = overflow

Brad

Reply via email to