Article From:

For example:

printf("%d\n" , 10 << 3);

I know how to deal with this small displacement, 10 converted to the original code, and then add 3 0 later, in the conversion to the decimal system, that is the result.


printf("%d\n" , 10 << 31)

10 The binary representation of1010,The length is 4. If10 >> 31,If the normal complement is 31 0, then the length is31 + 4 = 35 Position, obviously more thanintType 10 Maximum number of digits32bitc How do you deal with this displacement?

Answer 0:

CLogical displacements and arithmetical displacements in language standards

In the C language, there are 2 operators involving displacement.>>To move to the right,<<It indicates left shift.
And in the assembly instruction,SHLandSHRIt represents the logic left shift and the logical right shift,SARandSALIt represents the arithmetic left and the arithmetic right shift.
Among them, the left shift of logic and the left shift of arithmetic are the shift of register binary digit to the left and the complement of 0 on the right side.
While the right shift is different, the logical right shift is the overall shift to the right, and the 0 on the left side, while the arithmetic shift to right is based on the value of the original symbol bit and its same value.

So how do we implement logical and arithmetic shifts in C language? According to the C standard, if the variables on the left side of the displacement operator are signed numbers, such asint, char, shortThe compilation instructions generated by the compiler are arithmetic shift instructions, if the variable is unsigned.unsigned int, unsigned charThe compilation instructions generated by the compiler are logical displacement instructions.

Shift instruction

SAL(shift arithmetic left) Arithmetic left shift
Format:SAL, OPR, CNT
Meaning: arithmetic left shiftSALTo shift the low position of the target operand to the high position and to vacate the low bit complement 0..62Hby01100010B,The displacement is only in ordinary understanding to move the binary bits to the left or to the right, and the number of moves is determined by the operator to abandon or put the vacant position, the vacant position is determined by the operator for 0 or the number of the moved.

As you can know, the underlying execution10 << 31At that time, the part beyond the length will be discarded and then added to the original space 0.

Leave a Reply

Your email address will not be published. Required fields are marked *