Shift operations on signed numbers

During arithmetic shifting, the sign bit of the number should be kept unchanged, and the magnitude of the value should be changed. Shifting one bit to the left is equivalent to multiplying the number by 2, and shifting one bit to the right is equivalent to dividing the number by 2.

There are three types of shift operations: arithmetic shift, logical shift, and circular shift. Each shift can be divided into left shift and right shift.

 

1. Arithmetic shift

The object of arithmetic shifting is a signed number, and the sign of the operand must be kept unchanged during the shifting process. If there is no overflow when shifting one bit to the left, the value is multiplied by 2; when shifting one bit to the right,

1.1 Original code shifting rules

Regardless of positive or negative numbers, when shifting left or right, the sign bit remains unchanged, and the vacant positions are all filled with "0".

The results before and after shifting the source code of negative numbers are as follows:

Left shift: before the shift has   1 X_1X_2...X_{n-1}X_{n}

           After the shift there is   1 X_2X_3...X_{n}0           

Right shift: before the shift has   1 X_1X_2...X_{n-1}X_{n}

           After the shift there is   10X_1...X_{n-2}X_{n-1}

1.2 Complement code shift rule

(1) positive number

The sign bit remains unchanged, regardless of left or right shift, the vacant position will be filled with "0"

(2) Negative numbers

 Left shift: before the shift has   1 X_1X_2...X_{n-1}X_{n}

            After the shift there is   1 X_2X_3...X_{n}0           

Shift right: Before the shift has   1 X_1X_2...X_{n-1}X_{n}

            After the shift there is   11X_1X_2...X_{n-2}X_{n-1}

2. Logical shift

The object of the logical shift is an unsigned number, so there is no need to consider the sign issue when shifting.

When the logic is shifted to the left, the high bit is lost, and the low bit is filled with "0"; when the logic is shifted to the right, the low bit is lost, and the high bit is filled with "0".

3. Cyclic shift

The cyclic shift can be divided into two types according to whether it is shifted together with the carry bit: a small cycle without a carry bit, and a large cycle with a carry bit

Guess you like

Origin blog.csdn.net/qq_59109986/article/details/127816613