home | list info | list archive | date index | thread index

Re: [OCLUG-Tech] twos complement & signed types ??

  Hey,



On 9/22/07, Ian! D. Allen <idallen [ at ] idallen [ dot ] ca> wrote:
> Perhaps one thing that is missing in this conversation is the fact that
> when the ALU adds one to any memory value, the same thing always happens.
> Basic integer math doesn't care about sign.  There is no concept, at the
> ALU level, of "signed" or "unsigned".  It's all just bits being added.
...
> For addition (or subtraction) it doesn't matter if the variable is signed
> or unsigned - when you say "x = x + 1" the ALU just adds one to the bits
> in memory and sets some CPU flags.  Signed, unsigned, same thing.

Just for fun, I compiled and disassembled the code.
For anyone interested:

intadd.c
----
#include <stdio.h>
#include <stdlib.h>


int s_add() {
   signed int sx = 2000000000;
   signed int sy = 2000000001;
   signed int sz = sx + sy;
//   printf("sz is 0x%x which could be %d or %u\n", sz, sz, sz);
}

int us_add() {
   unsigned int ux = 2000000000;
   unsigned int uy = 2000000001;
   unsigned int uz = ux + uy;

//   printf("uz is 0x%x which could be %d or %u\n", uz, uz, uz);
}

int main(int c, char *v[]) {
  s_add();
  us_add();

  exit(0);
}

gcc -o intadd intadd.c
 objdump -S -D intadd > intadd.asm

Shows:
08048374 <s_add>:
 8048374:       55                      push   %ebp
 8048375:       89 e5                   mov    %esp,%ebp
 8048377:       83 ec 10                sub    $0x10,%esp
 804837a:       c7 45 f4 00 94 35 77    movl   $0x77359400,0xfffffff4(%ebp)
 8048381:       c7 45 f8 01 94 35 77    movl   $0x77359401,0xfffffff8(%ebp)
 8048388:       8b 45 f8                mov    0xfffffff8(%ebp),%eax
 804838b:       03 45 f4                add    0xfffffff4(%ebp),%eax
 804838e:       89 45 fc                mov    %eax,0xfffffffc(%ebp)
 8048391:       c9                      leave
 8048392:       c3                      ret

08048393 <us_add>:
 8048393:       55                      push   %ebp
 8048394:       89 e5                   mov    %esp,%ebp
 8048396:       83 ec 10                sub    $0x10,%esp
 8048399:       c7 45 f4 00 94 35 77    movl   $0x77359400,0xfffffff4(%ebp)
 80483a0:       c7 45 f8 01 94 35 77    movl   $0x77359401,0xfffffff8(%ebp)
 80483a7:       8b 45 f8                mov    0xfffffff8(%ebp),%eax
 80483aa:       03 45 f4                add    0xfffffff4(%ebp),%eax
 80483ad:       89 45 fc                mov    %eax,0xfffffffc(%ebp)
 80483b0:       c9                      leave
 80483b1:       c3                      ret

So you can see that the assembly is indeed identical in the two functions
and therefore sign independent. I won't try to explain each line of the
UGLY x86 assembly. ;-)

The interested (obsessive?) reader can
add in  the signed/unsigned comparison and see what assembly is
generated.

-- 
// Randy