Convert between a double and byte array to pass through the ZigBee API?

I try to take two two-local (GPS coordinates) and send them via the ZigBee API to another ZigBee receiver, but I don’t know how to decompose paired bits into byte arrays, and then recompile them back to their original form after they are transferred.

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

Any ideas?

+4
source share
3 answers

What you do is called type punning .

Use the union:

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

Or use reinterpret_cast :

 char* b = reinterpret_cast<char*>(d); 
+4
source

Here is a pretty unsafe way to do this:

 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 can use 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 
+3
source

Usually double - it's already eight bytes. Please check this on your operating system by comparing sizeof (double) and sizeof (char). C ++ does not declare a byte , usually it means char

If this is true.

  double x[2] = { 1.0 , 2.0}; double* pToDouble = &x[0]; char* bytes = reinterpret_cast<char*>(pToDouble); 

Now bytes are what you need to send to ZigBee

+1
source

Source: https://habr.com/ru/post/1380315/


All Articles