299 views
2 votes
2 votes

#include <stdio.h> int main() { int i = -1; int x = (unsigned char)i; printf("%d", x); return 0; }

output is 255 , but please explain how

1 Answer

7 votes
7 votes

$\text{i = -1 => }$${\boxed{1111 \ \ 1111}\boxed{1111 \ \ 1111}\boxed{1111 \ \ 1111}\boxed{1111 \ \ 1111}} \ \ (32 \ bits)$ 

$\text{we are converting "int"(32 bits) into "unsigned char" (8 bits) so "truncation" will happen i.e }$

$\underset{\text{32 bits}}{\boxed{1111 \ \ 1111}\boxed{1111 \ \ 1111}\boxed{1111 \ \ 1111}\boxed{1111 \ \ 1111}}⇒$ $\underset{\text{truncated 8 bits}}{\boxed{ \ 1111 \ \ 1111 \ }}$

$\text{Now its storing inside "int" again, so "bit extension" will happen and due to unsigned, remaining bits will be filled with "0"}$

$i.e \  \ \boxed{ \ 1111 \ \ 1111 \ } ⇒ $ $\boxed{0000 \  \ 0000}\boxed{0000 \ \ 0000}\boxed{0000 \ \ 0000}\boxed{1111 \ \ 1111} ⇒ 2^{8} - 1 = + \ 255$

$\newline$

$\color{Orange}\text{Output : }$ 255 

Related questions

0 votes
0 votes
2 answers
1
Debargha Mitra Roy asked Apr 16
174 views
#include <stdio.h int main() { int a[3] = {1, 3, 5, 7, 9, 11}; int *ptr = a[0]; ptr += sizeof(int); printf("%d", *ptr); return 0; }(Assume size of int to be $2$ bytes.)T...
0 votes
0 votes
2 answers
3
Debargha Mitra Roy asked Apr 10
189 views
What is the output of the below code?#include <stdio.h void main() { static int var = 5; printf("%d ", var ); if (var) main(); }a. 1 2 3 4 5b. 1c. 5 4 3 2 1d. Error
2 votes
2 votes
1 answer
4
rupamsardar asked Aug 30, 2023
508 views
#include <stdio.h int f(int x) { if(x%2==0) { return f(f(x-1)); } else return (x++); } int main() { printf("%d",f(12)); ret...