|
Casting double to bytes |
Ariesnl
Member #2,902
November 2002
|
When I need to serialize a double to a byte stream and vice versa I use these functions in C ( and C++) 1DoubleToBytes(double a_dDouble)
2{
3 std::vector<uint8_t> vResult;
4 const unsigned char *pBtyeArray = reinterpret_cast<const unsigned char*>(&a_dDouble);
5 const unsigned char *pBtyeArrayEnd = pBtyeArray + sizeof(double) -1;
6
7 for (; pBtyeArray <= pBtyeArrayEnd; pBtyeArray++)
8 {
9 unsigned char b = *pBtyeArray;
10
11
12 vResult.push_back(*pBtyeArray);
13 }
14
15 return vResult;
16}
17
18BytesToDouble(std::vector<uint8_t> a_zByteArray)
19{
20 double dNumber;
21 memcpy(&dNumber, a_zByteArray.data(), sizeof(double));
22 return dNumber;
23}
This works great as long as sender and receiver are programmed in C or C++. Any Ideas ? Perhaps one day we will find that the human factor is more complicated than space and time (Jean luc Picard) |
Dizzy Egg
Member #10,824
March 2009
|
In C# you would just use the BitConverter 1 public byte[] ConvertDoubleToByteArray(double d)
2
3 {
4
5 return BitConverter.GetBytes(d);
6
7 }
8
9 public double ConvertByteArrayToDouble(byte[] b)
10
11 {
12
13 return BitConverter.ToDouble(b, 0);
14
15 }
---------------------------------------------------- |
Edgar Reynaldo
Major Reynaldo
May 2007
|
You're forgetting endianness of the machines. My Website! | EAGLE GUI Library Demos | My Deviant Art Gallery | Spiraloid Preview | A4 FontMaker | Skyline! (Missile Defense) Eagle and Allegro 5 binaries | Older Allegro 4 and 5 binaries | Allegro 5 compile guide |
|