In the program below i initiliaze i to 255
Thus in Binary we have:
0000 0000 1111 1111
That is in Hex:
0x 0 0 f f
So according to Little-Endian layout:
The Lower Order Byte – 0xff is stored first.
#include<cstdio>
int main()
{
int i=0x00ff; //I know 0xff works. Just tried to make it understable
char *cptr=(char *)&i;
if(*(cptr)==-127)
printf("Little-Endian");
else
printf("Big-Endian");
}
So, when i store the address of i in cptr it should point to the Lower Byte (assuming Little Endian, coz that is what my System has) .
Hence, *cptr contains 1111 1111. This should come down to -127. Since, 1 bit is for the Sign-bit.
But when i print *cptr‘s value i get -1, why is it so?
Please explain where am i going wrong?
Where did you get the idea that
1111 1111is-127? Apparently, you are assuming that the “sign bit” should be interpreted independently from the rest of the bits, i.e. setting the sign bit in binary representation of+127should turn it into-127, right? Well, a representation that works that way does indeed exist: it is called Signed Magnitude representation. However, it is virtually unused in practice. Most modern machines use 2’s Complement representation for signed types, which is a completely different thing.On a 2’s-complement machine
1111 1111has always been-1.-127would be1000 0001. And1000 0000is-128, BTW.On top of that keep in mind that
chartype is not necessarily signed. If you specifically need a signed type, you have to spell it out:signed char.