Faster Checked Signed Addition in C#

Signed Integer Overflow Detection

A similar method can be developed for summation of signed long arrays.

When adding singed integers, arithmetic overflow is possible. In fact, arithmetic underflow is also possible – where adding two negatives results in a positive value.

When adding two signed integers, four cases are possible:

  • both positive
  • both negative
  • first positive and second negative
  • first negative and second positive

For the last two cases, where the two values are of opposite sign, arithmetic overflow is not possible. For the case where both values are positive, the check is needed to see if the resulting sum is smaller – same as for the unsigned sum above. For the case where both values are negative, the check is needed to see if the resulting sum is larger than either of the values being summed.

Performance Benchmarks

TODO: Present long array sum performance with overflow on every sum (positive only and negative only), and with no overflow (32-bit int randoms, maybe also positive only 32-bit randoms and negative only 32-bit randoms): to Decimal, single-core and multi-core implementation

Other Integer Data Types

Just like for integer, unsigned and signed, data types, overflow can be detected for other integer data types, such as long and ulong, or short and ushort. Implementing overflow detection is especially useful for long and ulong integer data types, because there is no bigger integer CPU-native data types available in most programming languages. For summing of long and ulong arrays Decimal and BigInteger C# software data types are available, both of which provide more bits of precision to not cause overflow. HCPsharp supports fast single-core, multi-core and SIMD/SSE summation of long and ulong arrays.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s