It appears that you were not understanding the information given in the comments, so here is an example which shows you that it doesn't matter if it was initially stored as a "decimal" or "hexadecimal"
short short1 = 0x10;
short short2 = 16;
short short3 = (short) (short1 + short2);
System.out.println("Short1: " + short1 + ", " + Integer.toHexString(short1));
System.out.println("Short2: " + short2 + ", " + Integer.toHexString(short2));
System.out.println("Short3: " + short3 + ", " + Integer.toHexString(short3));
Output:
Short1: 16, 10
Short2: 16, 10
Short3: 32, 20
EDIT:
In response to your comment I have added an example of going from an int
to a short
using two different methods. What you seem to be getting caught on is that the int should be in hexadecimal value
; this is not how values are stored (doesn't matter whether it is int, short, long, etc.). All of these types are stored internally as two's complement integers (See this post). Thus in the example below both int1
and int2
represent the same value
int int1 = 0x01b213d4; // Stored as: 1101100100001001111010100
int int2 = 28447700; // Stored as: 1101100100001001111010100
short short1Cast = (short) int1;
short short1Mask = (short) (int1 & 0xFFFF);
short short2Cast = (short) int2;
short short2Mask = (short) (int2 & 0xFFFF);
System.out.println("Int1: " + int1 + ", " + Integer.toHexString(int1) + ", " + short1Cast + ", " + short1Mask);
System.out.println("Int2: " + int2 + ", " + Integer.toHexString(int2) + ", " + short2Cast + ", " + short2Mask);
Output:
Int1: 28447700, 1b213d4 | Short1: 5076, 5076
Int2: 28447700, 1b213d4 | Short2: 5076, 5076
I have kept both the cast method and mask method in here because you explicitly made reference to masking the integer value. Unless you have to do something special with bit masking, I would highly suggest using the easier cast approach as there is no functional difference in the output value.