7/19/2016

double memcpy to byte, example. useful in serial communication

When we program the serial communication,
You may want to send double number in bytes, rather than strings.

In other words,
when we have 123123123123.123123123123 double value.
it is better send value to byte of sizeof(double), rather than the 25byte string.

The following example further, an example that sends a double 3 dogs as a byte.
...
double x = 1234.4567+10;
  double y = 2345.6789+10;
  double z = 3456.7891+10;

  char sendingStr[sizeof(double) * 3];

  memcpy(sendingStr, &x, sizeof(double));
  memcpy(sendingStr + sizeof(double), &y, sizeof(double));
  memcpy(sendingStr + sizeof(double) * 2, &z, sizeof(double));

  m_Comm.WriteComm((BYTE*)sendingStr, sizeof(double) * 3);
...


In addition, if there is the data to be send prefix is as follows.
...
double x = 1234.4567+10;
  double y = 2345.6789+10;
  double z = 3456.7891+10;

  char sendingStr[sizeof(double) * 3 + 2];
  sendingStr[0] = '_';
  sendingStr[1] = 'E';

  memcpy(sendingStr + 2, &x, sizeof(double));
  memcpy(sendingStr + 2 + sizeof(double), &y, sizeof(double));
  memcpy(sendingStr + 2 + sizeof(double) * 2, &z, sizeof(double));

  m_Comm.WriteComm((BYTE*)sendingStr, sizeof(double) * 3 + 2);
...

And so if you want to change the byte sent back to double is when you do the following:
...
double Mx, My, Mz;
   memcpy(&Mx, MxyzStr, sizeof(double));
   memcpy(&My, MxyzStr+sizeof(double), sizeof(double));
   memcpy(&Mz, MxyzStr + sizeof(double)*2, sizeof(double));
...

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete