Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2012

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Reading Single and Double reals in Little-endian and Big-endian

  • To: mathgroup at smc.vnet.net
  • Subject: [mg125175] Re: Reading Single and Double reals in Little-endian and Big-endian
  • From: "Oleksandr Rasputinov" <oleksandr_rasputinov at ymail.com>
  • Date: Sun, 26 Feb 2012 04:19:55 -0500 (EST)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • References: <jhldir$ot7$1@smc.vnet.net> <jhsu7g$np4$1@smc.vnet.net>

On Fri, 24 Feb 2012 06:02:04 -0000, ezh <dgolber at aol.com> wrote:

> Yes, I need to reverse the byte order.  After all, it's not a PC
> storing the stuff read from the file, it's Mathematica.

I see. Well, your problem is caused by the Utilities`BinaryFiles` package,  
which reads binary files in a fairly insane way and hard-codes an  
assumption of big-endianness when dealing with reals. This code was  
written over 20 years ago (in 1991) and is now well and truly obsolete. On  
the plus side, the package source (in  
AddOns/StandardPackages/Utilities/BinaryFiles.m) can be edited as you see  
fit, including to add support for little-endian reals. So, for example, in  
the package we find the following definition which provides for reading a  
single precision number:

rb[stream_InputStream,Single,_] :=
   floatvalue @@ {Quotient[#1,128],
         (Mod[#1,128])*2 + Quotient[#2,128],
         ((Mod[#2,128])*256^2 + #3*256 + #4)/(2^23) + 1}& @@
       Read[stream,{Byte,Byte,Byte,Byte}]

Reading the rest of the package source, we note that the third argument  
corresponds to endianness, with True meaning big-endian, and False,  
little-endian. So, we make the needed changes:

rb[stream_InputStream,Single,bigendian_] :=
   floatvalue @@ {Quotient[#1,128],
       (Mod[#1,128])*2 + Quotient[#2,128],
       ((Mod[#2,128])*256^2 + #3*256 + #4)/(2^23) + 1}& @@
     If[bigendian,Identity,Reverse]@Read[stream,{Byte,Byte,Byte,Byte}]

and, just like that, we have support for little-endian single precision  
numbers (or at least, I hope so--I didn't test this). Do the same for  
double precision numbers and you're finished updating the package.

I hope this fixes your problem so that workarounds are no longer needed.  
However, I still think that using Import to start with rather than trying  
to read the file manually would have been easier, as well as avoiding this  
bizarre problem.



  • Prev by Date: Re: Importing data from the web
  • Next by Date: Re: FindMinimum v. NMinimize and an external program
  • Previous by thread: Re: Reading Single and Double reals in Little-endian and Big-endian
  • Next by thread: NDSolve slow when using generic function definition