retagged by
1,019 views
1 votes
1 votes
#include <stdio.h>

int main(void){
    int i=511;
    char *p = (char *)&i;
    printf("%d", *p);
}

OK so why take 2's complement and not simple binary number? Means, why is C giving -1 and not 255?

retagged by

1 Answer

0 votes
0 votes
2's complement form is used by C,Because it is the efficeint way to represent positive and negative number in a given bit space.

int i=511; it means i=0000000111111111 in binary(as int takes 16 bits);

when you type cast it in char only 8 bits are saved (as char takes only 8 bits in 2's complement form)

now i =11111111; which is (2^7-1)-2^7=-1;

Related questions

1 votes
1 votes
0 answers
2
0 votes
0 votes
3 answers
3
Vasu Srivastava asked Aug 18, 2017
703 views
#include <stdio.h void f(int,int); int main(void){ int a = 5; f(a,a); printf("%d",a); } void f(int x, int y){ x ; y=y+15; }If copy-restore is used, then what will be the ...
0 votes
0 votes
1 answer
4
Psnjit asked Jan 12, 2019
1,137 views
main(){unsigned int i= 255;char *p= &i;int j= *p;printf("%d\n", j);unsigned int k= *p;printf("%d", k);} Both the outputs are -1. I have even tried with - int i = 255(3rd ...