in Programming in C
414 views
2 votes
2 votes

As we know any negative number is stored in c language in 2's complement form.

as for example:-
 

#include <stdio.h>

int main() {
    int x=-12;
     printf("%d\n",x);
     x=(~12);
     printf("%d",x);
	return 0;
}



Question URL=> http://code.geeksforgeeks.org/mBXMen

12(decimal form)

0000 1100(binary form)

-12=> 2's compliment(0000 1100 ->(flip bits)=1111 0011+(1)=1111 0100(stored in memory))

Q1). when we print -12 then how it print -12.(after storing -12 into 2's compliment)

Q2).how ~(12) prints -13

in Programming in C
414 views

1 Answer

3 votes
3 votes
Best answer

As you supposed int is 8 bit i will be explaining whole thing considering int as 8 bit :
12 = 0000 1100       -12 is 1111 0100
when it comes to printing it first see MSB to find out +ve -ve if MSB = 1 the its -ve 
Now comes magnitude after MSB whatever there is part of magtidude and is calculated again in terms of 2's compliment
111 0100 is magnitude part calculate its 2's compliment it will give 000 1100     so it will print -ve(sign) 12(magnitude)

here is your 2nd ques ~12 = ~(0000 1100) = 1111 0011
MSB = 1  sign = -ve
Magnitude = 2's compliment of 111 0011 = 000 1101 = 13
final answer -13 
Hope it helps :D

selected by
by