I'm building a hex calculator in objective-c. My problem is dealing with long long values that would overflow when multiplied.
When I add values before I add i check that the value would not overflow by doing something like this.
long long leftToAdd = LLONG_MAX - self.runningTotal;
if (self.selectedNumber <= leftToAdd) {
self.runningTotal += self.selectedNumber;
} else {
self.selectedNumber -= leftToAdd;
self.runningTotal = self.selectedNumber-1;
self.overflowHasOccured = YES;
}
if the value would overflow it takes the overflow value (without actually overflowing) and adds an overflow notification. I was hoping to find a way to do this same type of thing but for multiplication, can anyone help with this?
here's what i have so far.
// if - value would not overflow //
if (self.runningTotal > 0 && self.selectedNumber > 0
&& LLONG_MAX/self.runningTotal >= self.selectedNumber) {
self.runningTotal *= self.selectedNumber;
// else - handle overflow //
} else {
}
and as a side question would i need to do a similar check for division?