-4

We had a Unix code to create diameter file from .xml file as input. As we have moved to Linux platform we need to create same utility, code was compiled successfully but utility is not creating output file content as expected the bits are reversed in order for every byte , i think its because Linux is little endian.

Message block to be written to output file is of format :

ACE_Message_Block* mb = m_pReqMsgBlock;
while (mb) {
                out.write(mb->rd_ptr(), mb->size());
                mb = mb->cont();
           }

Can anyone suggest what extra can be added to code so that bytes can be written in expected manner ?

PU.
  • 148
  • 9
  • 5
    "Linux is little endian" - No, that is your machine! If your code relies on a specific representation of the data, it is just badly written. Use proper serialisation with bitshifts and never rely on implementation specific behaviour. – too honest for this site Jun 14 '16 at 12:02
  • Try seeing if reversing each bit will help. http://stackoverflow.com/questions/2602823/in-c-c-whats-the-simplest-way-to-reverse-the-order-of-bits-in-a-byte. Note this should only be done when transporting the file to a system with a different endianess. – Giorgian Borca-Tasciuc Jun 14 '16 at 12:05
  • 1
    And what was the previous platform? And please specify your actual and expected output. – Jabberwocky Jun 14 '16 at 12:05
  • What type does `mb->rd_ptr()` return? – dbush Jun 14 '16 at 12:11
  • @dbush its ACE_Message_Block – PU. Jun 14 '16 at 12:29

2 Answers2

5

You will have to convert from big endian format to the little endian format. This will have to be done separately for 16 bit and 32 bit values in the structure.

Functions like htons and htonl can be used to convert 16 bit and 32 bit integers respectively.

Once the numbers are converted, then it can be written via the write function.

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
  • I already tried this but data to be written is not integer, its from external library that we are using ACE class ACE_Message_Block – PU. Jun 14 '16 at 12:28
  • You need to look at the structure elements of ACE_Message_Block, and convert each element one at a time as shown above. Note that 8 bit values are the same in big endian and little endian. – Rishikesh Raje Jun 15 '16 at 05:09
0

If you're writing binary data to a file, the 'correct' endianness of that binary data is machine-specific. So it's correct that this data is different if it's run on a machine with another endianness. You probably parse this binary data again with another program on the same Linux machine, which will also expect it to be little-endian.

If you want the output to be endian-agnostic (e.g. because the program that reads the data is on your big-endian unix machine), you should not output binary data.

Bartez
  • 172
  • 8