5

I'm a little confused as to how longs work in C.

If I ask for the maximum value of a long in Java I get a number in the quintillions. If I ask for it in C, signed or unsigned, it's in the billions.

Java is built on C... so where is the difference coming from?

I've also tried representing literals with long long values, unsigned/signed long values and long int values. None of them seem to handle numbers past the mid-billions. Why? Am I making a mistake?

1

3 Answers 3

10

The C standard defines long to be at least as large as int. The actual size is implementation dependent. This is not the case for Java, in which long is required to be 64 bits long.

The C99 standard defines fixed size integer types like int64_t defined in stdint.h that you can use if you need fixed size integers on all platforms.

3
  • Just to add a comment: It usually depends on the bits of your operating system, but of course the doesn't have to be the case.
    – dimme
    Dec 24, 2011 at 4:29
  • Can I use a 64bit long in the standard C library?
    – bgroenks
    Dec 24, 2011 at 4:40
  • 1
    @ghostsoldier23 You can use 64 long for libraries which take 64-bit values, usually requiring your program be compiled as 64-bit e.g. when size_t is 64-bit. Dec 24, 2011 at 7:56
2

C also has the long long type. That one is guaranteed to be at least 64 bit.

4
  • C99 defines long long int to be at least be able to hold 64 bit signed integers and greater than the size of long int. It isn't necessarily 64 bit. Dec 24, 2011 at 13:55
  • @MehrdadAfshari, right, I was not precise enough, thanks, changed. Dec 24, 2011 at 13:59
  • @Mehrdad: you said, in effect, that the size of long long int must be strictly greater than the size of long int; is that correct? Surely, a conforming implementation can provide long long int the same size as long int; the size of long long int cannot be less than the size of long int. Dec 24, 2011 at 22:08
  • @JonathanLeffler not strictly. Greater as in ">=" which is what I wrote in my answer--but long int should at least be 32 bits and long long int should be at least 64 bits. If a conforming implementation is about to use the same size for both, it can, however, both should be at least 64 bits in that case. Dec 24, 2011 at 22:58
0

If you want to work with bigger numbers you can use the GNU MP Bignum Library here: http://gmplib.org/ The numbers and the precision is only limited by available memory of the machine that it runs on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.