tags:

views:

1430

answers:

5

Hi,

Can anyone send me a c code to divide 2 64bit numbers. My compiler only supports 32/32 division.

Thanx & Regards

Mani

+5  A: 

The code is available in linux, see div64.c. Can you copy that?

1800 INFORMATION
This code is only exact for 64-bit / 32-bit. For 64-bit / 64-bit it is willing to accept a "small" error in favor of speed (so you'll get a fast result, but it is not exact).
Mecki
+8  A: 

Are you positive your compiler doesn't support 64-bit division? If your C compiler supports C99, this should work:

#include <stdint.h>
#include <stdio.h>
int main(void)
{
    int64_t numerator = 123;
    int64_t denominator = 10;
    int64_t quotient = numerator / denominator
    printf("%" PRId64 " / %" PRId64 " = %" PRId64 "\n",
           numerator, denominator, quotient);
    return 0;
}
Tom
No, the intX_t types are POSIX extension to C99. And even in POSIX, only the < 64 bit types are required. See http://www.opengroup.org/onlinepubs/9699919799/basedefs/stdint.h.html
ysth
"long long" is in C99, and is guaranteed to be at least 64 bits.
ShreevatsaR
@ysth: intX_t are part of standard C99 and int64_t is required if the implementation provides a two's complement 64-bit integer. You can also use int_least64_t which is required in C99 and guaranteed to be at least 64-bits.
Robert Gamble
@ysth: Not true! stdint.h is defined in the C99 standard (search wikipedia for stdint.h). It used to be a POSIX extension, it became standard C. BTW u_int64_t is still a POSIX extension, only uint64_t is C standard (note the extra underscore).
Mecki
+3  A: 

A more general idea is to use a multi-precision library, like GMP.

GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. GMP has a rich set of functions, and the functions have a regular interface.

Floating point division is handled with void mpf_div (mpf_t rop, mpf_t op1, mpf_t op2)

gimel
A: 

More than likely, the division limitation stems from the fact that you're compiling for 32-bit instead of 64-bit.

I don't recall seeing an integer division instruction that handles 64 bit for x86. It would multiply 2 32-bit integers, and split the results across 2 registers, but not division as far as I recall..

Calyth
C abstracts the processor. He's not looking to divide in assembly, or natively on the processor. He just wants to divide. Even on systems without a 'div' instruction (or similar), division is supported (properly) per C standards.
strager
64 bit division on x86 post- Athlon64 and P4 Xeon is `divq`.
Crashworks
A: 

Looking elsewhere in the Linux kernel: udivdi3.c

This should be accurate supplies the functions used by GCC whenever it encounters a 64 bit division.

Steven