C language binary (original code, inverse code, complement code)

1. Storage, classification

Integer binary includes: original code, complement code, complement code. Generally, what is stored in memory is the complement code.

2. The relationship between the original, inverse and complement of positive and negative numbers

Integers are divided into positive numbers and negative numbers.

The original code of a positive number = complement code;

The same is not true for negative numbers :

Negative number's inverse code = the original code sign bit remains unchanged, and the other bits are reversed bit by bit

The complement of a negative number = the complement of a negative number + 1;

3. Sign bit (determine positive or negative)

The binary of an integer is judged positive or negative by the first digit, that is, the sign bit. If the first digit is 1, it is a negative number; if the first digit is 0, it is a positive number.

4. The relationship between binary and decimal systems

Binary to decimal:
Positive number: Multiply the binary number from the right to the left by the power of 2, such as 00101010 to decimal:

(0 * 2 to the zero power) + (1 * 2 to the first power) + (0 * 2 to the second power) + (1 * 2 to the third power) + (0 * 2 to the fourth power) + (1 * 2 to the 5th power) + (0 * 2 to the 6th power) + (0 * 2 to the 7th power) = 0 + 2 + 0 + 8 + 0 + 32 + 0 + 0 = 42

Negative numbers: first subtract 1 and negate it, then calculate the decimal

For example, 1101011 is a negative number, like converting to decimal, then subtract one and invert to 00010101, and then calculate the corresponding decimal to 21, so the final result is -21.

Decimal to binary

Use the "divide by 2 and take remainder, arrange in reverse order" method:

1. First divide a decimal integer by 2 to get a quotient and remainder

2. Then use 2 to divide the obtained quotient, and you will get a quotient and remainder

3. Repeat the operation until the quotient is less than 1

4. Then arrange all the remainders obtained, and then reverse it (arrange in reverse order), remember to be reversed!

Suppose we now need to convert 42 to binary, how do we do it, as follows

    • number of binary digits

In the C language, for the shift, and, or, XOR symbols, it is necessary to write a complete binary, so how many are there in a binary? This generally depends on the type in front of the number. If the number is of int type, int occupies 4 bytes, and one byte has 8 bits. Therefore, the memory of this number is 32 bits, which is composed of 32 numbers. To form a binary number, 0 is usually added in front.

Guess you like

Origin blog.csdn.net/m0_75115696/article/details/128851701