in Programming in C retagged by
634 views
5 votes
5 votes
#include <stdio.h>
int main()
{
    int i= 255;
    short int *s= (short int *)&i;
    printf("%d\n", *s);
}


What will be the output of the above program in little-endian and big-endian, respectively?

$(65280\text{ is } 255\times2^8)$

  1. $255,\; 0$
  2. $65280,\; 0$
  3. $0,\;0$
  4. $0,\; 65280$
in Programming in C retagged by
634 views

1 Answer

4 votes
4 votes

$i$ = 255, since int is $4B$

 which in binary is $0\text{x}11111111$

short int *s = (short int *) &i; Since short is 2B it will point to only $16$ bits.

If it is stored in Little-endian then least significant byte is stored in the lowest address. s will point to initial $2B$ that is$11111111$ $00000000$ = $255$

If it is stored in Big-endian then most significant byte is stored in the lowest address. s will point to $2B$ that is $00000000$ $00000000$ = $0$

by

4 Comments

edited by
in little-endian 11111111 00000000 = 65280  then why the answer is 255 please clarify.

got it: it will reverse and then be converted to decimal as it is stored after reversing the original no then it will print.

where in big-endian it is already stored in a similar fashion so it will be directly converted to decimal and printed.
1
1
I need to confirm one doubt:
short (2 Bytes) will point to first 16 bits from left-to-right, irrespective of the fact that 255 (4 Bytes) is in big-endian or little-endian representation.
Is this correct?
0
0
And also, the information about 65280 in the question seems to be irrelevant. isn't it?
1
1
edited by

@Shubhamishere yes but in little-endian representation of 255 first 16 bits will be 11111111 00000000 and in big-endian first 16 bits will be 00000000 00000000.

That information is given just to confuse you like in little-endian data will be stored like 11111111 00000000 but LSB is stored at the least address so while printing it will be treated as 00000000 11111111 (just for understanding) which is 255 but if someone just convert it directly 11111111 00000000 which will be equal to 65280

4
4
Answer:

Related questions