Write a program to determine whether a computer is big-endian or little-endian.
bool endianness() {
int i = 1;
char *ptr;
ptr = (char*) &i;
return (*ptr);
}
So I have the above function. I don’t really get it. ptr = (char*) &i, which I think means a pointer to a character at address of where i is sitting, so if an int is 4 bytes, say ABCD, are we talking about A or D when you call char* on that? and why?
Would some one please explain this in more detail? Thanks.
So specifically, ptr = (char*) &i; when you cast it to char*, what part of &i do I get?
If you have a little-endian architecture,
iwill look like this in memory (in hex):If you have a big-endian architecture,
iwill look like this in memory (in hex):The cast to
char*gives you a pointer to the first byte of the int (to which I have pointed with a^), so the value pointed to by thechar*will be01if you are on a little-endian architecture and00if you are on a big-endian architecture.When you return that value,
0is converted tofalseand1is converted totrue. So, if you have a little-endian architecture, this function will returntrueand if you have a big-endian architecture, it will returnfalse.