Frage

#include<stdio.h>

int main()
{
    int a=32;
    printf("%d\n", ~a);  //line 2
    return 0;
}

o/p = -33

Actually in the original snippet line 2 was

 printf("%x\n", ~a);  //line 2

I solved it like

32 in hex is 20.
0000 0000 0010 0000
now tilde operator complements it
1111 1111 1101 1111 = ffdf.

I am confused how to solve it when I have

printf("%d\n", ~a);  //line 2 i.e %d NOT %x.
War es hilfreich?

Lösung

In your C implementation, as in most modern implementations of any programming language, signed integers are represented with two’s complement.

In two’s complement, the high bit indicates a negative number, and the values are encoded as in these samples:

Bits  Decimal
0…011 +3
0…010 +2
0…001 +1
0…000  0
1…111 -1
1…110 -2
1…101 -3

Thus, if the usual (unsigned) binary value for the bits is n and the high bit is zero, the represented value is +n. However, if the high bit is one, then the represented value is n-2w, where w is the width (the number of bits in the format).

So, in an unsigned 32-bit format, 32 one bits would normally be 4,294,967,295. In a two’s complement 32-bit format, 32 one bits is 4,294,967,295 - 232 = -1.

In your case, the bits you have are 1111 1111 1111 1111 1111 1111 1101 1111. In unsigned 32-bit format, that is 4,294,967,263. In two’s complement, it is 4,294,967,263 - 232 = -33.

Andere Tipps

You should print out unsigned integers with the %u specifier:

unsigned int a = 32;
printf("%u\n", ~a);

Printing it out with %d treats it as a signed integer.

You see it as a negative number because the sign bit is set from 0 to 1 through the binary negation.

Printing it out as a hex number doesn't interpret the sign bit, so you see the same result in both cases.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top