tags:

views:

325

answers:

2

Hello,

From a C program on Windows we need to read and write like a Java bytebuffer which stores binary in BIG_ENDIAN

The algorithm is described at : http://mindprod.com/jgloss/binaryformats.html

Need to read and write int and float.

Does anyone have example c or C++ code that does this or a reference ?

TIA, Bert

+1  A: 

I assume the difficulty is in converting between Big Endian and Little Endian.

This article should help you out with the Endian conversions. It contains code to swap the byte order on integers, long integers, floating point numbers, and byte arrays of arbitrary length.
http://www.codeproject.com/KB/cpp/endianness.aspx

The code to swap an arbitrary type looks like this:

#include <algorithm> //required for std::swap

#define ByteSwap5(x) ByteSwap((unsigned char *) &x,sizeof(x))

void ByteSwap(unsigned char * b, int n)
{
   register int i = 0;
   register int j = n-1;
   while (i<j)
   {
      std::swap(b[i], b[j]);
      i++, j--;
   }
}
Robert Harvey
A: 

You want to use htonl and similar. The rest of design is your own.

Arkadiy
Note: htonl() would be used for a 32-bit integer, htons() would be used for a 16-bit integer, and a (single btye) 8-bit integer would not need to be byte-swapped, obviously.
Mike
... and I should add that this solution will not work for a Java "long" (typically 'long long' in C) - you would need to use Robert's generic ByteSwap function.
Mike