handling overflow in Objective C - objective-c

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?

You could check for overflow in multiplication following the same pattern you use for addition - for the later you use subtraction to determine the bound, for the former you would use division:
long long canMultiplyBy = LLONG_MAX / self.runningTotal;
In all cases if you are supporting signed numbers you have to consider underflow as well. Division requires a divide by zero check.
In the C library there are functions for checked arithmetic, lookup check_int64_mul to find the lot (they are all described on the same manual page). These will be efficient and operate directly with primitive value types are you are now doing.
The Clang compiler also provides some checked arithmetic builtin functions, these differ from the C library functions in returning a bool indications and being defined for int, long and long long types rather than int32 and int64. See Checked Arithmetic Builtins.
There are also NSDecimal - a value type, and NSDecimalNumber - an object type built over the former. These provide both extended precision, up to 38 decimal digits, and control over overflow, underflow, divide-by-zero, etc. See NSDecimalNumberBehaviors and NSDecimalNumberHandler.
HTH

Related

Kotlin - Type conversion with overflow exceptions

(123L).toInt() produces 123 but Long.MAX_VALUE.toInt() produces -1. Clearly this is not correct. Without having to write a lot of boilerplate code, is there a way to get Kotlin to throw an exception when a value is out of range/bounds for the target type?
TL;DR you can make a custom extension function that checks if the value is between Int.MIN_VALUE and Int.MAX_VALUE
fun Long.toIntThrowing() : Int {
if (this < Int.MIN_VALUE || this > Int.MAX_VALUE) {
throw RuntimeException()
}
return this.toInt()
}
The "weird" behavior you are observing is happening, because in Kotlin, Long is represented as a 64 bit signed integer, while Int is represented as a 32 bit signed integer.
While 123L is easily representable by a 32 bit integer, Long.MAX_VALUE will overflow the Integer (almost) twice, resulting in the behavior you are observing.
I believe the example below will illustrate it better:
println((2147483647L).toInt()) // the max 32 bit signed int
println((2147483648L).toInt()) // 1 more overflows it to the min (negative) 32 bit signed int
println((2147483649L).toInt()) // 2 more...
println((Long.MAX_VALUE - 1).toInt())
println((Long.MAX_VALUE).toInt())
results in :
2147483647
-2147483648
-2147483647
-2
-1
From: https://discuss.kotlinlang.org/t/checked-and-unsigned-integer-operations/529/2
Exceptions on arithmetic overflow: this will likely make arithmetics significantly slower, and we don’t see how to avoid it without changes to the JVM, nor are we ready to accept the slowdown
If you are running on the JVM you may use Math.toIntExact:
Returns the value of the long argument; throwing an exception if the value overflows an int.
There doesn't seem to be a pure Kotlin way, but at least you can nicely wrap it:
fun Long.toIntExact() = Math.toIntExact(this)

Allow Addition Overflow in vb.net

I'm working on a vb.net app that needs to add multiple integers together. The integers are to be unsigned, and 32 bits in length.
It is expected that the integers will be so large that they will overflow when addition takes place. If any overflow does occur, I don't want to store any of the overflow, or there to be any exceptions that occur.
For example, If I was working with 4 bit numbers, I would want the following behaviour:
1111 + 0010 = 0001
I've tried the following to see what happens on an overflow - I get an overflow exception. Is there any elegant way around this?
Dim test As UInt32 = UInt32.MaxValue
Console.WriteLine(test.ToString())
test = test + 1
Console.WriteLine(test.ToString())
I'm currently using UInt32 to represent the integers, however this can be changed if somebody knows a better type.
It's important that the overflow bits are not stored, as later on I will want to perform bit shifts, etc on these numbers.
I can see the obvious solution of converting between UInt64 and UInt32, however I may have to expand the app in the future to use 64 bit numbers (so it would be nice to have a solution that's easily expandable)
Thanks in advance,
Dave
You can use the "Remove integer overflow checks" option in "Project" -> "<project name> Properties..." -> "Compile" tab -> "Advanced Compile Options..."
Dim a As UInt32 = UInt32.MaxValue
a += 1
Console.WriteLine(a) ' outputs 0
You will have to use 64 bit integers (they may be called Longs in your version of VB).
Dim Value1 As Long = 12345
Dim Value2 As Long = 67890
Dim Result As Long = Value1 + Value2
' Remove the overflow from the result
Console.WriteLine(Result AND &HFFFF)
You can use either signed or unsigned integers, but you will have to double your storage to make it work (e.g., 16 to 32).

How to store too large binary value in objective-c? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have got a too large binary value.
value1 : 2 ^ 300,000.
value2 : 2 ^ 300,000.
I'd like to do 'and calculation' of value1 and value2.
First of all, how to store a value1 and value2? (int, float, double... ???)
int value1 = 2 ^ 300000;
Is this correct?
Does this way completly store a value?
context for using)
I have two arrays which has 300,000 elements.
eg) array1 # [# "apple", # "banana", # "iphone", # "TV", # "clock" .... <= it has 300, 000.
array2 # [# "fruit", # "fruit", # "electric", # "electric", # "electric" ....] <= also has 300,000.
display prefered thing to binary : 1,1,0,0,1 ...
display prefered kind to binary : 1,1,0,0,0 ...
result of calculating 'and' of array1 & array2 : 1,1,0,0,0 ...
I like "apple" and "banana" of fruit.
Reason of using binary calculating are expected to be faster than other way.
The first thing is that you are not using Objective-C classes, but Plain Old Datatype, a.k.a. POD.
That large value far exceeds the limit of integers, even 64-bit unsigned ints. I am not a math wiz, so I'm not sure if that will fit in a double but that doesn't matter because with floating-point, you loses precision. (Link to WolframAlpha for the exact value that definitely won't fit.)
What you want is probably NSDecimalNumber which provide up to 38 digit precision, that's what's built into the library, if you need further precision, you can write your own class, or check out libraries like GMP.
There's a good question and answer about NSDecimalNumber here.
UPDATE: As Craig mentioned in the comment, you may want to roll your own class to speed up the calculation. Libraries like GMP are general purpose, and will do the calculation in a way that's so safe that it sometimes are wasting your time as the calculation you want to do can be simplified.
First of all the ^ operator is not a power operator, but a bitwise XOR.
So 2 ^ 300000 actually produces 300002.
Secondly you can use NSDecimalNumber, a subclass of NSNumber, which according to the documentation
provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127
If you have 300 000 objects, have you considered to use a database, e.g. Core Data? Instead of a very large bit mask, maybe it would be easier to do the same by a single database (Core Data) request.
To answer your specific question, a C-array of integers would be probably the best solution:
const NUM_OBJECTS = 300000;
//8 * sizeof(int) bits per an int
int* mask = malloc((size_t) ceilf(NUM_OBJECTS / (sizeof(int) * 8.0f));

Difference between Objective-C primitive numbers

What is the difference between objective-c C primitive numbers? I know what they are and how to use them (somewhat), but I'm not sure what the capabilities and uses of each one is. Could anyone clear up which ones are best for some scenarios and not others?
int
float
double
long
short
What can I store with each one? I know that some can store more precise numbers and some can only store whole numbers. Say for example I wanted to store a latitude (possibly retrieved from a CLLocation object), which one should I use to avoid loosing any data?
I also noticed that there are unsigned variants of each one. What does that mean and how is it different from a primitive number that is not unsigned?
Apple has some interesting documentation on this, however it doesn't fully satisfy my question.
Well, first off types like int, float, double, long, and short are C primitives, not Objective-C. As you may be aware, Objective-C is sort of a superset of C. The Objective-C NSNumber is a wrapper class for all of these types.
So I'll answer your question with respect to these C primitives, and how Objective-C interprets them. Basically, each numeric type can be placed in one of two categories: Integer Types and Floating-Point Types.
Integer Types
short
int
long
long long
These can only store, well, integers (whole numbers), and are characterized by two traits: size and signedness.
Size means how much physical memory in the computer a type requires for storage, that is, how many bytes. Technically, the exact memory allocated for each type is implementation-dependendant, but there are a few guarantees: (1) char will always be 1 byte (2) sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long).
Signedness means, simply whether or not the type can represent negative values. So a signed integer, or int, can represent a certain range of negative or positive numbers (traditionally –2,147,483,648 to 2,147,483,647), and an unsigned integer, or unsigned int can represent the same range of numbers, but all positive (0 to 4,294,967,295).
Floating-Point Types
float
double
long double
These are used to store decimal values (aka fractions) and are also categorized by size. Again the only real guarantee you have is that sizeof(float) <= sizeof(double) <= sizeof (long double). Floating-point types are stored using a rather peculiar memory model that can be difficult to understand, and that I won't go into, but there is an excellent guide here.
There's a fantastic blog post about C primitives in an Objective-C context over at RyPress. Lots of intro CPS textbooks also have good resources.
Firstly I would like to specify the difference between au unsigned int and an int. Say that you have a very high number, and that you write a loop iterating with an unsigned int:
for(unsigned int i=0; i< N; i++)
{ ... }
If N is a number defined with #define, it may be higher that the maximum value storable with an int instead of an unsigned int. If you overflow i will start again from zero and you'll go in an infinite loop, that's why I prefer to use an int for loops.
The same happens if for mistake you iterate with an int, comparing it to a long. If N is a long you should iterate with a long, but if N is an int you can still safely iterate with a long.
Another pitfail that may occur is when using the shift operator with an integer constant, then assigning it to an int or long. Maybe you also log sizeof(long) and you notice that it returns 8 and you don't care about portability, so you think that you wouldn't lose precision here:
long i= 1 << 34;
Bit instead 1 isn't a long, so it will overflow and when you cast it to a long you have already lost precision. Instead you should type:
long i= 1l << 34;
Newer compilers will warn you about this.
Taken from this question: Converting Long 64-bit Decimal to Binary.
About float and double there is a thing to considerate: they use a mantissa and an exponent to represent the number. It's something like:
value= 2^exponent * mantissa
So the more the exponent is high, the more the floating point number doesn't have an exact representation. It may also happen that a number is too high, so that it will have a so inaccurate representation, that surprisingly if you print it you get a different number:
float f= 9876543219124567;
NSLog("%.0f",f); // On my machine it prints 9876543585124352
If I use a double it prints 9876543219124568, and if I use a long double with the .0Lf format it prints the correct value. Always be careful when using floating points numbers, unexpected things may happen.
For example it may also happen that two floating point numbers have almost the same value, that you expect they have the same value but there is a subtle difference, so that the equality comparison fails. But this has been treated hundreds of times on Stack Overflow, so I will just post this link: What is the most effective way for float and double comparison?.

Objective-C - Is !!BOOL Beneficial

I'm looking over the diffs submitted to a project by another developer, and they have a lot of code that does !!<some BOOL value>. In fact, this seems to be their standard pattern for implementing boolean getters and setters. They've implemented their code like:
- (BOOL) hasId {
return !!hasId_;
}
- (void) setHasId:(BOOL) value {
hasId_ = !!value;
}
I've never seen this pattern before, and am wondering if there is any benefit in using it. Is the double-negation doing anything useful?
The double boolean operator just makes sure that the value returned is either a 1 or a 0. That's all : )
! is a logical negation operator. So if setHasId: was passed, eg., 0x2 then the double negation would store 0x1.
It is equivalent to:
hasId_ = value ? 1 : 0;
It is useful in some cases because if you do this:
BOOL x = y & MY_FLAG;
You might get 0 if MY_FLAG is set, because the result gets truncated to the size of a BOOL (8 bits). This is unexpected. For the same reasons, people sometimes prefer that BOOL is either 0 or 1 (so bit operations work as expected). It is usually unnecessary.
In languages with a built-in bool type such as C (as of C99) and C++, converting an integer to bool does this automatically.
It makes more sense in some other cases for example where you are returning BOOL but don't want to put an if statement in.
- (BOOL)isMyVarSet
{
return !!myVar;
}
In this case I can't just return myVar because it's not a BOOL (this is a very contrived example - I can't dig out a decent one from my projects).
I've used this before and I believe:
if (!!myVar)
is equivalent to:
if (myVar != nil)
Basically, I use it to verify the value of SOMETHING.
I will admit... this is probably not the best practice or most-understood way to accomplish this goal.