binary

Link: https://www.nowcoder.com/questionTerminal/ca7818b6a6734b10989883b0eb47c126
Source: Niuke.com

1. In Java, it is expressed in two's complement form
2. The first bit is positive and negative, 1 means negative, 0 means positive.
3. Original code: the binary representation of a number.
                 3's original code 00000011 -3's original code 10000011
4. Inverse code: Invert the original code of the negative number bit by bit (the sign bit remains unchanged). The positive original code itself.
                3's complement 00000011 -3's complement 11111100
5. Complement code: The positive number is the original code itself. Add 1 to the complement of a negative number.
                 3's complement is 00000011 - 3's complement is 11111101
-------------------------------------------------------------------------------
int occupies 4 bytes, 32 bits
byte occupies 1 byte, 8 bits
So it will be truncated when forced. top 24
---------------------------------------------------------------------------
Representation in memory ( note that in java a number is represented as a complement, so the representation is a complement, not the original code! ):
int a = 3         00000000  00000000  00000000 00000011 (the first 24 0s are truncated when the byte is forcibly converted)
byte b = 3      00000011
int a = -3 11111111  11111111 11111111 11111101 (the first 24 1s are truncated when the byte is forcibly converted)    
byte b = -3     11111101
----------------------------------------------------------------------------
Knowing the complement of a negative number, find the negative number:
Complement -1 = inverse code, inverse code bitwise = absolute value of the negative number
Given a negative number, find the complement of the negative number:
1. In addition to the sign bit, the original code of the negative number is reversed by bit (excluding the sign bit), and 1 is added.
2. The complement of the absolute value of the negative number (that is, the original code), inverse bitwise (including the sign bit), and add 1
-------------------------------------------------------------------------------
example:
Convert java int 128 to byte, value:
128 is a positive number, and its complement is 10000000 (the first 24 0s are omitted), and it becomes a byte, leaving only 10000000 (byte is 1 byte), because the beginning is 1, so it is a negative number. That is, the 1's complement of a negative number is 10000000. The inverse code is 01111111, and the original code is 1000000. is 128. Because it is a negative number, it is -128.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326147740&siteId=291194637