0

I have two processes called P1 and P2. In P1, I read data from a file and write it to a shared memory region. The code is as follows:

#include <fstream>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
using namespace std;
using namespace boost::interprocess;

int main()
{
    ifstream file;
    file.open("sigData.bin", ios::binary | ios::in);

    shared_memory_object shm(open_or_create, "shared_memory", read_write);
    shm.truncate(1024*1024);
    mapped_region region(shm, read_write);

    unsigned char * mem = static_cast<unsigned char*> (region.get_address());

    /* Write data to shared memory */
    file.read(reinterpret_cast<char*> (mem), region.get_size());
}

The data read from the binary file is as follows:

6419 0000 9ce6 0000 6419 0000 9ce6 0000 ...

In process P2, I need to read this data as unsigned shorts. So, when I read the data, the shorts are byte-swapped.

shared_memory_object tx1_shm(open_only ,"shared_memory", read_write);
mapped_region tx1_region(tx1_shm, read_write);
unsigned short* mem2 = static_cast<unsigned short*> (tx1_region.get_address());

/* Print the first 4 shorts */
for (int i = 0; i < 4; i++)
{
    printf("0x%04x\n", *mem2);
    mem2++;
}

The output of the printing is as follows:

1964 0000 e69c 0000 1964 0000 e69c 0000 

Whereas if I read the data as bytes, they are read correctly. How do I read the unsigned shorts directly?

Mobi Zaman
  • 605
  • 1
  • 6
  • 19
  • They are byte-swapped because your system is little endian. Bytes ARE same, but when two bytes are interpreted to shorts, on littleendian first byte is least significant one. – Swift - Friday Pie Sep 09 '22 at 06:56

0 Answers0