in Programming edited by
230 views
2 votes
2 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 edited by
230 views

2 Answers

4 votes
4 votes

Answer: A

Big Endian: Table of address and data in hex

int i
1000 1004 1008 1012
00 00 00 FF

 

s points to address 1000. Since s is a short pointer it will read data from 1000 – 1007 which is all zeroes: 0

Little Endian: Table of address and data in hex

int i
1000 1004 1008 1012
FF 00 00 00

In this scenario also s points to the address 1000. In little endian bytes are stored in reverse but those are also read in reverse.

s reads the data from 1000 – 1007 which is oxFF 00. It is first reversed 0x00 FF and then interpreted.: 255

 

3 Comments

Hey what does it meant by typecasting the address

i mean  this (short int *)&i;

whats the difference between (short int *)&i; and (short int )i;
0
0

Typecasting is just a hint to the compiler. The thing you should understand is that pointer always has the base address of “object”, now what sense to make of that bit pattern and/or how many bits to read depends on the type of pointer.

 

&i in this case is 1000, that’s is, from this address you can not say for sure if this is the address of int, char, array, structure…

 

short *ptr = &i;
// Implicitly typecasted as 
short *ptr = (short *)&i;
// because of the type of “ptr”, though there will be a 
// warning if you don’t cast it explicitly.

whats the difference between (short int *)&i; and (short int )i;

First works with pointer and second one with variables.

short *ptr = (short *)&i;
short s = (short)i;

In second case however s is new variable storing the value at some other location.

0
0

After reversing the 2 bytes (16 bits) of little-endian. Integer promotion will also happen since %d is used in printf() which is 32 bits signed integer and sign extension will happen based on MSB, which is 0 here in this case. So, finally, printf() will print this interpretation of 32 bits (4 bytes) of signed integer i.e: 255.

00000000 00000000 00000000 11111111

Have I described this whole process correctly? Please correct me if anything is wrong.

0
0
3 votes
3 votes
Answer : A
For more information about Little and Big endian refer the below video, the above question also solved in the video by Sachin Sir
 
 
Answer:

Related questions