Casting double to bytes
Ariesnl

When I need to serialize a double to a byte stream and vice versa I use these functions in C ( and C++)

#SelectExpand
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++.
However, in my case right now the receiving end is programmed in C#...::)
And I have a hard time converting the byte array to double again.
Nothing seems to work...

Any Ideas ?

Dizzy Egg

In C# you would just use the BitConverter

#SelectExpand
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

You're forgetting endianness of the machines.

Thread #618459. Printed from Allegro.cc