Why when casting int c = 10000 to the type byte , the value of the variable becomes 16 , not 128 , the maximum value of byte ?

 int c = 10000; byte d = (byte) c; System.out.println(d); 

    2 answers 2

    You do not quite understand how type conversion occurs.

    When casting int to byte , the “best fit” calculation does not occur. It is different: the “high bytes” are simply discarded.

    10000 = 0x2710 consists of two bytes: 0x27 and 0x10. The most significant byte is discarded, the least significant 0x10 = 16 remains.

    • I do not quite understand, do not tell me what to read on this topic in order to better deal with older, younger bytes, and since further in this thread. It probably does not belong to the programming language at all but to some basics of the programming itself? - Maksim Korkodinov
    • @MaksimKorkodinov: I don’t even know, to be honest. Maybe some good tutorial on pure C? In a C byte device, you just have to know everything by heart. - VladD
    • Obviously, you will not learn this in java, not a low-level language.) - Maksim Korkodinov
    • one
      @MaksimKorkodinov, read about the binary number system, how many bits are in a byte, what values ​​can a byte take, how many can be pushed into 2 bytes, etc. - Russtam

    Because in byte you can cram a maximum of 255. You have an overflow of the discharge grid. The size of the type byte is 256 . Find the number that comes after the cast is simple - just take the module:

     10000 % 256 = 16; 
    • Why take a module? - Maksim Korkodinov
    • @MaksimKorkodinov this is me as an example, in order to understand what will be in the end. - Suvitruf ♦
    • one
      @MaksimKorkodinov because the operation of taking the remainder modulo 256 returns the low byte - Pavel Mayorov