i was asked by private message to explain my example. maybe its interesting for someone else ...
2 things to know here
1)
every number tipe in
java is signed,
so the first bit corresponds to the sign of that number:
0 is positive, 1 is negativ
2)
Explicit casting bigger types (eg an int to a byte) removes the leading bits.
e.g. you have a int (32 bit) 00000000 00000000 00000000 00000011 (3)
after casting to byte (8 bit) : 00000011 (still 3)
But if you habe a longer number (eg 130), you loose information:
00000000 00000000 00000000 10000010 (130)
becomes 10000010
here the leading sign is positive, but (ups)a positiv sign means a negative number!!! (see above)
To find out, how a negative number is calculated, you can look
here (but its not relevant for exam, i hope)
in short : substitute every bit with its complement
(here we get 01111101) and add 1
(we get 01111110) which corresponds to 126. As we know it is a negative number (see above) it has to be -126
but again: dont worry about for exam.
to play around, you can use e.g. Integer's parse()-Method with 2 parameters, first a binary
String ("01111110") that a 2 (for binary)
You can print out the decimal number than...
regards