Section 5.21. Numerical Computation of a Definite Integral


5.20. Determining the Architecture's Byte Order

It is an interesting fact of the computing world that we cannot all agree on the order in which binary data ought to be stored. Is the most significant bit stored at the higher-numbered address or the lower? When we shove a message over a wire, do we send the most significant bit first, or the least significant?

Believe it or not, it's not entirely arbitrary. There are good arguments on both sides (which we will not delve into here).

For more than twenty years, the terms little-endian and big-endian have been applied to the two extreme opposites. These apparently were first used by Danny Cohen; refer to his classic article "On Holy Wars and a Plea for Peace" (IEEE Computer, October 1981). The actual terms are derived from the novel Gulliver's Travels by Jonathan Swift.

Most of the time we don't care what byte order our architecture uses. But what if we do need to know?

The following method determines this for us. It returns a string that is LITTLE, BIG, or OTHER. It depends on the fact that the l directive packs in native mode, and the N directive unpacks in network order (or big-endian).

def endianness   num=0x12345678   little = "78563412"   big    = "12345678"   native = [num].pack('l')   netunpack = native.unpack('N')[0]   str = "%8x" % netunpack   case str     when little       "LITTLE"     when big       "BIG"     else       "OTHER"   end end puts endianness   # In this case, prints "LITTLE"


This technique might come in handy if, for example, you are working with binary data (such as scanned image data) imported from another system.




The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net