#-- # ByteOrder # # Copyright (c) 2003 Michael Neumann # # ========================================================================== # Revision History :: # -------------------------------------------------------------------------- # 2005.04.28 TO * Minor modifications to documentation. # ========================================================================== # # :NOTE: This seems like a little much for what's really a single method. # In the future this should be reduced and moved to Nano Methods. # Only reason I haven't done so yet, is b/c BinaryReader # depends on it. # #++ #:title: ByteOrder # # ByteOrder module makes it possible to determine your systems # byte order, either big or little endian. # # == Usage # # ByteOrder.byteorder => :LittleEndian # # == Author(s) # # * Michael Neumann # # module ByteOrder Native = :Native BigEndian = Big = Network = :BigEndian LittleEndian = Little = :LittleEndian # examines the byte order of the underlying machine def byte_order if [0x12345678].pack("L") == "\x12\x34\x56\x78" BigEndian else LittleEndian end end alias_method :byteorder, :byte_order def little_endian? byte_order == LittleEndian end def big_endian? byte_order == BigEndian end alias little? little_endian? alias big? big_endian? alias network? big_endian? module_function :byte_order, :byteorder module_function :little_endian?, :little? module_function :big_endian?, :big?, :network? end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin testing # By Michael Neumann require 'test/unit' class TC_ByteOrder < Test::Unit::TestCase def test_equal assert_equal ByteOrder.little?, ByteOrder.little_endian? assert_equal ByteOrder.big?, ByteOrder.big_endian? assert_equal ByteOrder.network?, ByteOrder.big_endian? assert_equal ByteOrder.byte_order, ByteOrder.byteorder assert_equal ByteOrder::Big, ByteOrder::BigEndian assert_equal ByteOrder::Network, ByteOrder::BigEndian assert_equal ByteOrder::Little, ByteOrder::LittleEndian assert_equal ByteOrder.byte_order, ByteOrder::LittleEndian if ByteOrder.little? assert_equal ByteOrder.byte_order, ByteOrder::BigEndian if ByteOrder.big? end def test_uname_byteorder assert_equal(ByteOrder.little?, true) if `uname -m` =~ /i386/ end def test_byteorder if ByteOrder.little? assert_equal "\x12\x34\x56\x78".unpack("L").first, 0x78563412 assert_equal "\x78\x56\x34\x12".unpack("L").first, 0x12345678 assert_equal [0x12345678].pack("L"), "\x78\x56\x34\x12" assert_equal [0x78563412].pack("L"), "\x12\x34\x56\x78" else assert_equal "\x12\x34\x56\x78".unpack("L").first, 0x12345678 assert_equal "\x78\x56\x34\x12".unpack("L").first, 0x78563412 assert_equal [0x12345678].pack("L"), "\x12\x34\x56\x78" assert_equal [0x78563412].pack("L"), "\x78\x56\x34\x12" end end end =end