Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

how does c compiler handle unsigned and signed integer? Why the assembly code for unsigned and signed arithmetic operation are the same?

I am reading the book: CS-APPe2. C has unsigned and signed int type and in most architectures uses two's-complement arithmetic to implement signed value; but after learning some assembly code, I found that very few instructions distinguish between unsigned and signed. So my question are:

  1. Is it the compiler's responsibility to differentiate signed and unsigned? If yes, how does it do that?

  2. Who implements the two's-complement arithmetic - the CPU or the complier?

Add some more info:

After learning some more instructions, actually there are some of them differentiate between signed and unsigned, such as setg,seta,etc. Further, CF and OF apply to unsigned and respectively. But most integer arithmetic instructions treat unsigned and signed the same,e.g.

int s = a + b

and

unsigned s = a + b

generate the same instruction.

So when executing ADD s d, should the CPU treat s&d unsigned or signed? Or it is irrelevant, because the bit pattern of both result are the same and it is the compiler's task to convert the underlying bit pattern result to unsigned or signed?

P.S i am using x86 and gcc

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In many cases there is no difference at the machine level between signed and unsigned operations, and it is merely a matter of interpretation of the bit pattern. For example consider the following 4-bit word operation:

Binary Add  Unsigned   2's comp
----------  --------   --------
  0011          3         3
+ 1011       + 11       - 5
-------     --------   --------
  1110         14        -2  
-------     --------   --------

The binary pattern is the same for the signed and unsigned operation. Note that subtraction is merely the addition of a negative value. When a SUB operation is performed, the right-hand operand is two's complemented (invert bits and increment) then added (the ALU circuit responsible is an adder); not at the instruction level you understand, but at the logic level, although it would be possible to implement a machine without a SUB instruction and still perform subtraction albeit in two instructions rather than one.

There are some operations that do require different instructions depending on the type, and it is the compiler's responsibility to generate appropriate code generally speaking - architectural variations may apply.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...