Skip to content
Advertisement

strange reuslt when adding integers in JAVA [closed]

I have some questions about adding integer in JAVA. I have in my code here to add the four numbers: i1, i2, i3, and i4 and put them in i5. But I got a very strange result. Could someone comments?

    int t1 = ((byte) 0xfe) << 24; // equals to -33554432
    int t2 = (((byte) 0xcf) & 0xff) << 16; // equals to 13565952
    int t3 = (((byte) 0x81) & 0xff) << 8; // equals to 33024
    int t4 = (byte) 0x31; // equals to 49
    int t5 = t1 + t2 + t3 + t4; // NOW: why this sum equals to 16711680? I thought
    // this should match the decimal number given by 0xfecf8131 which
    // should be -19955407 (i.e. -19955407 = -33554432 + 13565952 + 33024 + 49)
    int total = 0xfecf8131; // this gives -19955407, so this is printed correctly 
    System.out.println("t1: " + t1);
    System.out.println("t2: " + t2);
    System.out.println("t3: " + t3);
    System.out.println("t4: " + t4);
    System.out.println("This should be expected result of i5: " + total);
    System.out.println("i5 = i1 + i2 + i3 + i4 is equal to : " + i5); // this gives 16711680 which seems not correct 

Basically what I was trying to do is to output the decimal of a hexadecimal form number like 0xfecf8131. But doing it by adding the contribution of 0xfe00000 and then 0x00cf0000, then 0x000081, then 0x00000031 since I have a program that would requires entering four bytes numbers such as: 0xfe, 0xcf, 0x81, 0x31 and those four will be taken as coming from the first position in memory, second in memory, third position in memory and fourth position in memory.

But I guess my main question is what is wrong with adding the 4 integers: t1, t2, t3, t4

using this way: int t5 = t1 + t2 + t3 + t4?

Advertisement

Answer

Works as expected on my computer. Are you sure you are not mixing i variables and t variables? On the last line you are using i5 and not t5.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement