[Thread Prev][Thread Next][Index]

Re: [ferret_users] choose little/big endian for stream binaryoutput



Hi there,

| Under UNIX (LINUX) one can use the dd utilily to swap bytes:
| 
|   dd if=in_file of=out_file conv=swab
| 
| This might be a solution.

I haven't tried this, but I suspect that it will work only
for binary files consisting of 2-byte objects.

A 4-byte floating point number, for example, which has a memory
layout of "|b0|b1|b2|b3|" is stored on the disk as
"|b3|b2|b1|b0|", if I remember correctly.  So, you have to swap
four bytes as a group, whereas the dd command swaps only
neighboring two bytes.

I heard there's a version of dd that has another swap option
for 2-, 4-, 8-byte objects:

   http://www.research.att.com/~gsf/man/man1/dd.html

The standard dd on Linux doesn't, unfortunately.

I don't know of any universal solution to the endianness conversion
problem.  I'm attaching my little quick & dirty C++ program to convert
binary files consisting of 4-byte objects only.  You can easily change
it for 8-byte objects.  This program is slow, I warn you.
(If there's sufficient demands, I could considerably speed it up.)

Ryo
===== endian4.cc ====================
// endian4.cc: convert 4-byte little endian to big endian (and vice versa)
//
// This is a pre-ANSI C++ program.  You may need to change
// <iostream.h> to <iostream>, cin to std::cin, and cout to std::cout .

#include <iostream.h>

typedef unsigned char uchar;

inline
void swap(uchar& a, uchar& b)
{
   const uchar tmp = a;
   a = b;
   b = tmp;
}

inline
void endian4(uchar* buf)
{
   swap(buf[0], buf[3]);
   swap(buf[1], buf[2]);
}


int main()
{
   uchar buf[4];
   for (;;) {
      cin.read(buf, sizeof(buf));
      endian4(buf);
      if (!cin) break;
      cout.write(buf, sizeof(buf));
   }
}

[Thread Prev][Thread Next][Index]

Dept of Commerce / NOAA / OAR / PMEL / TMAP

Contact Us | Privacy Policy | Disclaimer | Accessibility Statement