Hi Folks,
To determine if a machine is little endian / big endian the foll. code
snippet is used...
int num = 1;
if( * (char *)&num == 1)
printf ("\n Little Endian");
else
printf("\n Big endian");
You're right that code like this "is used" to make the test,
but it's unfortunate that you're right because the code is not
reliable. For example, it will always announce "Little Endian"
on a machine with 1-byte integers (like some DSP's). Also, it
considers only two possible outcomes; on a machine with 4-byte
int's there are twenty-four (of which at least three have been
used on actual, non-hypothetical hardware). Finally, there is a
(hypothetical) possibility that the correspondence between bit
values in an int and bit values in its constituent bytes is not
so simple; for a 32-bit int there are, in theory, 32 possible
ways the value 1 could be represented. All but one of those would
produce the reassuring but untrustworthy "Big Endian" answer.
As an early computer scientist put it, "There are more things
in heaven and earth, Horatio, than are dreamt of in your philosophy."
I needed a few clarifications regarding this.
1. Can we use void * instead of char * ?
No. (Try it!)
2. Does the above typecast convert an integer to a char (1 byte) in
memory?
For e.g if I used a variable ch, to store the result of the above
typecast
I don't understand your question. The cast (not "typecast")
converts an int* pointer value to a char* pointer value. There is
no way to tell whether this conversion happens "in memory" or in
a CPU register or in one of the watchtowers of Elsinore. You would
not try to store the cast's result (a pointer) in a char variable
(again, try it!), but you might do so with the value you get by
dereferencing that pointer.
3. In general, when can we safely do typecasts ? Is such code
portable ?
You can cast data pointer values to data pointer values of
different (or the same) types. You can cast function pointer
values to function pointer types. You can cast arithmetic values
to arithmetic types. And as a special case you can cast integers
(all kinds) to and from data pointers (all kinds).
BUT not all such conversions are meaningful. If you start
with a char* pointing at the 'd' in "Hello, world!", convert that
to a short, convert that to a double*, and try to use the pointer
that results, you are likely to get into trouble. The nature of
trouble you get into is non-portable (it might not even seem at
first to *be* trouble). Similarly, if you cast 1.2e30 to an int
you may be unhappy with the non-portable outcome.