Source: http: //blog.sina.com.cn/s/blog_6cbe0cff0101ekfl.html
public class Test { public static void main(String[] args) { int start = -131; int end = 131; for (int i = start; i < end; i++) if ((byte) i != i) System.out.println("原数:" + i + "\t转化后:" + (byte) i); } }
Original number: after -131 Conversion: 125 Number of Original: after -130 Conversion: 126 Number of Original: after -129 Conversion: 127 original number: 128 after conversion: -128 Number Original: 129 after conversion: -127 original number: 130 Conversion after: -126
Why does this happen?
Since the Java byte that represents only between -128 and 127 store 8 bits, when forced into the int type byte, the system taken after 8 taken int practice.
// store Java's complement integer, int type is a 32-bit, byte 8-bit @ 130 then representation in memory: 00000000 00000000 00000000 10000010 @ 8 taken after this becomes 10000010, the complement representation the first time is the sign bit, 0 positive 1 negative, // so you can know that is certainly a negative number 10000010, and then look at its value part, // complement the positive becomes negative, positive or negative change, methods: "bitwise, plus 1", // so it should become 1111101 0000010 + 1 = 1111110 (ie 126) // and because it is negative, so the interception becomes -126 // we look at -130 examples of (sign bit is 1, the remaining bitwise + 1) // --130 representation in memory: 1,111,111,111,111,111 1,111,111,101,111,110 // so taken after 8 becomes 01111110 // this is obviously an integer ah, then numerical part 126 // 64 + 32 + 16 + 8 + 4 + 2 = 126