signed and unsigned representation of data in memory?

-2

see the below code,

signed int a = 136; 
unsigned int b = -120; 

unsigned sum = a + b;
 printf("%d ", sum);

output- 16

according to my knowledge,

hex representation of

136 - ox88
-120 - ox88

1) SO IT SHOULD PRINT 0. ISN'T IT ?

2) how a -ve(signed) number is represented in memory as unsigned int ? is it like this,

-120 = 0xffffff88
136 = 0x00000088

if yes, in unsigned int range may have a value equal to "0xffffff88", so does it will conflict to each other ?

Can anyone explain the concept with example?(both signed and unsigned representation)

c
unsigned
signed
asked on Stack Overflow Jun 5, 2014 by Melvin • edited Jun 5, 2014 by Yu Hao

3 Answers

2

There is no need to guess about how things are represented in memory, and 2's complement arithmetic is endianness-agnostic.

Consider the following program.

#include <stdio.h>


int main(){
    signed int a = 136; 
    unsigned int b = -120; 

    unsigned sum = a + b;
    printf("a = 0x%x b = 0x%x sum = 0x%x\n", a,b, sum);
}

Output:

a = 0x88 b = 0xffffff88 sum = 0x10

In 2's complement, when we can sum a and b in binary without worrying about signs.

When we do the sum by hand, we will get a + b = 0x100000010. Since the first 1 overflows, it is simply dropped, leaving us 0x10, which is 16.

answered on Stack Overflow Jun 5, 2014 by merlin2011
0

your second binary representation is correct. adding this 2 binary numbers together you will get 0x10 in hex or 16 in decimal (and an overflow)

-120 in unsigned int will have the value 4 294 967 176 in 4 byte unsigned int

answered on Stack Overflow Jun 5, 2014 by mch
0
0xffffff88 +
0x00000088
----------
0x00000010 => 16

Also 1 in front of the result is discarded.

The 1 in second to last position in the result is from the carry by adding 8 + 8.

answered on Stack Overflow Jun 5, 2014 by George Nechifor

User contributions licensed under CC BY-SA 3.0