Convert between double and byte array, for transfer over ZigBee API?

lecreeg picture lecreeg · Nov 9, 2011 · Viewed 14.8k times · Source

I'm trying to take two doubles (GPS coordinates) and send them over the ZigBee API to another ZigBee receiver unit, but I don't know how to decompose the doubles into byte arrays and then re-compose them back into their original form once they are transferred.

Basically, I need to turn each double into an array of eight raw bytes, then take that raw data and reconstruct the double again.

Any ideas?

Answer

Pubby picture Pubby · Nov 9, 2011

What you're doing is called type punning.

Use a union:

union {
  double d[2];
  char b[sizeof(double) * 2];
};

Or use reinterpret_cast:

char* b = reinterpret_cast<char*>(d);