Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » Casting double to bytes

This thread is locked; no one can reply to it. rss feed Print
Casting double to bytes
Ariesnl
Member #2,902
November 2002
avatar

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 ?

Perhaps one day we will find that the human factor is more complicated than space and time (Jean luc Picard)
Current project: [Star Trek Project ] Join if you want ;-)

Dizzy Egg
Member #10,824
March 2009
avatar

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 }

----------------------------------------------------
Please check out my songs:
https://soundcloud.com/dont-rob-the-machina

Edgar Reynaldo
Major Reynaldo
May 2007
avatar

Go to: