Search code examples
javacastinglong-integer

Why casting a very large long number to int gives us a strange output (Java)?


I was practicing some castings in Java and I faced a situation for which I couldn't find any answers, anywhere. There are a lot of similar questions with answers, but none gave me an explanation for this particular case.

When I do something like

    long l = 165787121844687L;
    int i = (int) l;

    System.out.println("long: " + l);
    System.out.println("after casting to int: " + i);

The output is

long: 165787121844687
after casting to int: 1384219087

This result is very intriguing for me.

I know that the type long is a 64-bit integer, and the type int is a 32-bit integer. I also know that when we cast a larger type to a smaller one, we can lose information. And I know that there is a Math.toIntExact() method that is quite useful.

But what's the explanation for this "1384219087" output? There was loss of data, but why this number? How "165787121844687" became "1384219087"? Why does the code even compile?

That's it. Thanks!


Solution

  • 165787121844687L in hex notation = 0000 96C8 5281 81CF

    1384219087 in hex notation = 5281 81CF

    So the cast truncated the top 32 bits as expected.

                            32-bits 
                            deleted 
                           ▼▼▼▼ ▼▼▼▼
    165_787_121_844_687L = 0000 96C8 5281 81CF  ➣  1_384_219_087
        64-bit long                  ▲▲▲▲ ▲▲▲▲      32-bit int 
                                      32-bits 
                                     remaining