8

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?

lecreeg
  • 83
  • 1
  • 1
  • 4

3 Answers3

9

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);
Augustin
  • 2,444
  • 23
  • 24
Pubby
  • 51,882
  • 13
  • 139
  • 180
6

Here's a rather unsafe way to do it:

double d = 0.123;
char *byteArray = (char*)&d;

// we now have our 8 bytes

double final = *((double*)byteArray);
std::cout << final; // or whatever

Or you could use a reinterpret_cast:

double d = 0.123;
char* byteArray = reinterpret_cast<char*>(&d);

// we now have our 8 bytes

double final = *reinterpret_cast<double*>(byteArray);
std::cout << final; // or whatever
jli
  • 6,523
  • 2
  • 29
  • 37
1

Typically a double is already eight bytes. Please verify this on your operating system by comparing sizeof(double) and sizeof(char). C++ doesn't declare a byte , usually it means char

If it is indeed true.

   double x[2] = { 1.0 , 2.0};

   double* pToDouble = &x[0];
   char* bytes = reinterpret_cast<char*>(pToDouble);

Now bytes is what you need to send to ZigBee

parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85