in Programming in C
213 views
0 votes
0 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

in Programming in C
by
213 views

1 Answer

5 votes
5 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 

2 Comments

And is the behaviour the same on little-endian and big-endian machines?
0
0

@Arjun sir i think no, for little endian the byte ordering will be reversed. If we point a char ptr into it, then 1st byte will print -1 , 2nd byte 0 , and so on... 

int main() { 

    int i = -1; 

    int x = (unsigned char)i; 

    char *ptr = &x;

    printf("%d %d", *ptr, *(ptr+1));   // -1  0

    return 0; }

Sir correct me if anything wrong.

0
0

Related questions