code_unknown
code_unknown

Reputation: 33

Converting long to int gives 0

I have been testing out with this snippet of code:

public class Test {
    public static int longToInt(long num) {
        return (int) (num);
    }

    public static void main(String[] args) {
        System.out.println(longToInt(100000000L));
    }
}

I ran it but longToInt only returned 0. What is going on?

Upvotes: 0

Views: 1450

Answers (2)

Stephen C
Stephen C

Reputation: 718768

Casting a long to an int is done by removing the top 32 bits of the long. If the long value is larger than Integer.MAX_VALUE (2147483647) or smaller than Integer.MIN_VALUE (-2147483648), the net effect is that you lose significant bits, and the result is "rubbish".


Having said that, the code you supplied does not behave like you say it does ... if you compile and run it correctly. The original version should print an unexpected number ... but not zero. The modified version should print 1000000 as expected.


... is there a way I can store a long number larger than Integer.MAX_VALUE inside an int number?

No.

Well strictly yes ... in some circumstances. You could do something to map the numbers, For example, if you know that your numbers are always in the range A to B, and B - A is less than 232, then you could map a long in that range to an int by subtracting A from it.

However, it is mathematically impossible to define such a mapping if the size of the domain of numbers you are storing in the long is larger than 232. Which it typically is.

Upvotes: 1

Pandiri
Pandiri

Reputation: 329

because, the long you gave doesn't fit into int. Give a smaller long and try ! int (32 bits) long (64 bits)

Upvotes: 1

Related Questions