[C language] Integer binary and shift operators

 1. Binary

Binary is a base-2 notation system in mathematics and digital circuits. It is a binary system that uses base 2 as a representation system. In this system, it is usually represented by two different symbols: 0 (representing zero) and 1 (representing one). An integer is 4 bytes (that is, 32 bits), so the binary sequence of an integer is 32 bits.

  • For signed integers, the highest bit is the sign bit, a sign bit of 1 represents a negative number , and a sign bit of 0 represents a positive number .
  • For unsigned integers, there is no sign bit and all bits are significant bits.

There are three binary representations of integers : original code, complement code, and complement code.

  • Original code: The binary sequence written directly according to the positive and negative values ​​is the original code.
  • One's complement code: The sign bit of the original code remains unchanged, and other bits are not reversed.
  • Complement code: The complement code is obtained by adding 1 to the binary sequence of the complement code.

have to be aware of is:

  • For positive integers, the original code, complement code, and complement code are all the same , and no calculation is required.
  • For negative integers, the original code, complement code, and complement code need to be calculated according to the above method.
  • Regardless of whether it is a positive integer or a negative integer, as long as it is an integer, what is stored in the memory is a complement binary sequence, and the complement is also used when calculating.

2. Shift operator 

<< left shift operator

>> right shift operator

Note: The operands of the shift operator can only be integers.

1. Left shift operator

 Shift rule: discard the left side and add 0 to the right side.

 2. Right shift operator

  Shifting rules:

  • Logical shift: fill the left side with 0 and discard the right side
  • Arithmetic shift: The left side is filled with the sign bit of the original value (positive numbers are filled with 0, negative numbers are filled with 1), and the right side is discarded.

Note : Most compilers use arithmetic shifting, because when a number is negative, logical shifting will turn it into a positive number, which is too simple and violent.

Guess you like

Origin blog.csdn.net/zzzzzhxxx/article/details/132767057