Endianness, beautifully done
My
performance enthusiastic friend wrote an excellent
article (with working code) in how to determine the system's endianness and how to do swap bytes.
Out of curiosity, I browsed the Tcl source code to see how Tcl work out the global variable tcl_platform(byteOrder). Below code is extracted from tclBasic.c under the Tcl8.4.x source base. It is done beautifully and it really showed what Beautiful Code is all about.
..... union { char c[sizeof(short)]; short s; } order; ..... /* * Compute the byte order of this machine. */ order.s = 1; Tcl_SetVar2(interp, "tcl_platform", "byteOrder", ((order.c[0] == 1) ? "littleEndian" : "bigEndian"), TCL_GLOBAL_ONLY);
I extracted part of the code for verification.
#includeunion { char c[sizeof(short)]; short s; } order; int main(void) { order.s=1; printf("%s\n",order.c[0]==1 ? "littleEndian" : "bigEndian"); exit(0); }
On my Intel notebook, it is littleEndian and on the SPARC it is bigEndian. Of course it tallies with the Tcl global variable tcl_platform(byteOrder). In case you a Perl guy, this is how you can do it:
$is_big = unpack("h*", pack("s", 1)) =~ /01/; $is_little = unpack("h*", pack("s", 1)) =~ /^1/;
Labels: Endianness, Tcl
0 Comments:
Post a Comment
<< Home