Cast to a byte of type int

Cast to a byte of type int

int ii=666;
byte bb=(byte)ii;
System.out.println(bb);//打印得-102

Today encounter this problem when learning Java, baffled (forgive Masters just a material conversion, and consequently do not understand ~ ~), find someone to ask for a moment, can be considered resolved, the notes and share ideas.
First, before we resolve this question, to understand the concept of binary for binary numbers, the most significant bit (first from the left, such as the sign bit is the beginning of the left 10011010 1) is the sign bit, 0 for positive, 1 represents a negative value of the remaining portion of the true value.
because the most significant bit is a sign bit when the sign bit is 1, indicating that it is a negative number, the negative number is present in the computer's complement form, it is also necessary in terms of the original code . All numbers are present in the underlying computer in binary form, the original code is directly converted into a binary value, but in the form of computer code stored complement all integer
calculation rules complement. 1. complement positive numbers identical to the original code and
2. The negative is its anti-complement code plus 1; inverted original code is bitwise, only the most significant bit (sign bit) remains unchanged
in the sign bit is 1 (negative) Example
10001110 complement
inverse code conversion to complement, add 1 to obtain the inverted complement
10001101 the inverted
original code conversion to be inverted, the sign bit unchanged, the other bit inversion
11110010 original code

Back to this question can be interpreted as a 32bit (int) truncated to 8bit (byte), then go through the process of seeking a complement of
666 corresponds to 32bit binary 00000000 00000000 0,000,001,010,011,010
interception 8bit is 10011010, understood as follows: the first is the sign bit is 1, it is negative, the data bit is 0011010, Twos?
Complement (inverse code 1100101), after adding 1 to 1,100,110, corresponding to the decimal number 102, because the sign bit is negative, it is -102
WX public number (Chengxue Wen reading notes)

Published an original article · won praise 0 · Views 13

Guess you like

Origin blog.csdn.net/codeLearner_CXW/article/details/103949665