integer division towards -infinity

Discussion in 'C Programming' started by Sidney Cadot, Jul 10, 2003.

  1. Sidney Cadot

    Sidney Cadot Guest

    Hi all,

    As I understand it, the rounding direction of signed integer division
    in C is unspecified in C89/C94, and specified to be 'towards-zero' in
    C99.

    I need division 'towards -infinity' (with a 'mod' operation to match),
    i.e. for x and y I need to obtain D and M such that

    (1) D*abs(y)+M == x
    (2) 0 <= M<abs(y)

    For any signed x,y (y!=0).

    Is there a canonical way of doing this that is guaranteed to work in
    line with all C specifications?

    Best regards,

    Sidney Cadot
    The Netherlands
     
    Sidney Cadot, Jul 10, 2003
    #1
    1. Advertisements

  2. Did you think of using div_t div(int, int)? It does not round to
    minus infinity, but at least it rounds the same in both standards,
    IIRC.

    Best wishes,

    Bob
     
    Robert W Hand, Jul 10, 2003
    #2
    1. Advertisements

  3. Negative b, round to zero:

    div: -8/-5 - (-8%-5<0) == 1 - (-3<0) == 0
    mod: -8%-5 + -5*(-8%-5<0) == -3 + -5*(-3<0) == -8

    Fixed ones: (i think)

    div: a/b - (a%b<0 ? (b<0 ? -1 : 1) : 0)
    mod: a%b + (a%b<0 ? (b<0 ? -b : b) : 0)
     
    Jarno A Wuolijoki, Jul 11, 2003
    #3
  4. I usually use (a%b+b)%b for the mod case. I never needed the divide case,
    so I never tried that one.

    -- glen
     
    Glen Herrmannsfeldt, Jul 11, 2003
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.