Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using div with unsigned integers

Tags:

c++

c

division

The C++ standard provides div(int, int), but not udiv(unsigned int, unsigned int).

If I naively used unsigned ints in this function, I can see that this would yield the wrong result for integers greater than 2^31 - 1 in the numerator. For example (with 4-bit nibbles):

The largest 4-bit nibble is 15, 1111 in binary. As a signed nibble, this would represent -1. Dividing 15 by 2 yields 7, or 0111, but dividing -1 by 2 yields 0: 0000.

Is there a straightforward way to adapt div to unsigned integers, or am I better off writing my own udiv, or avoiding the use of div and div-like functions altogether?

Edit/Note: In my case, I'm using unsigned long long ints, so using lldiv doesn't solve the problem.

like image 361
castle-bravo Avatar asked Aug 28 '15 21:08

castle-bravo


People also ask

How do I cast to unsigned int?

To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.

What is the difference between signed and unsigned division?

Signed variables, such as signed integers will allow you to represent numbers both in the positive and negative ranges. Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive.

Can unsigned int have overflow?

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.


1 Answers

Back in the day, the result of / and % were not uniquely defined by C and div() was born. Now quotient from / is truncated towards 0.

unsigned math did not have this issue and so a lesser need for udiv().

Now many compilers recognize nearby a/b and a%b calculations and optimize quite well, reducing the need for even div(). Suggest just performing both calculations and let the compiler optimize it.


[Edit]
Detail: Prior to C99, division may truncate toward 0, toward INT_MIN or (maybe could round to nearest - I'll look into that). In any case % is the remainder after the division. div() was specified to only do one: divide with truncate toward 0. With C99, both div() and / perform a division with the quotient truncated toward 0.

See
What is purpose of the div() library function?
What is the behavior of integer division?

like image 170
chux - Reinstate Monica Avatar answered Oct 21 '22 14:10

chux - Reinstate Monica