Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# convert bytes to double with a "higher" precision

Tags:

c#

I always convert bytes to double with System.BitConverter.ToDouble() like this:

double value = BitConverter.ToDouble(flt, 0);//flt is an array of bytes.

But when I try to convert "8A 7F DA 0C 41 6D A6 40"(Little Endian),it become 2870.62705118949.

Indeed, 2870.62705118949 is "8E 7F DA 0C 41 6D A6 40".

But what I want is 2870.6270511894881565.How can I get the accurate value using C#?

like image 876
user42316 Avatar asked Feb 20 '16 14:02

user42316


1 Answers

When working with exact string representation, use "R" formatting:

https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx

"R" or "r" Round-trip Result: A string that can round-trip to an identical number.

In your case

  Byte[] data = { 0x8A, 0x7F, 0xDA, 0x0C, 0x41, 0x6D, 0xA6, 0x40 };

  Double value = BitConverter.ToDouble(data, 0);

  Console.Write(value.ToString("R", CultureInfo.InvariantCulture)); // "R" formatting

And as you can see, the actual value is not 2870.62705118949 but 2870.6270511894882; just compare the values:

  2870.6270511894882     Actual
  2870.6270511894881565  You want to have
  2870.62705118949       Proposed by changing 8A into 8E

and see that "8A 7F DA 0C 41 6D A6 40" is, in fact, a better choice (more accurate)

like image 74
Dmitry Bychenko Avatar answered Oct 18 '22 07:10

Dmitry Bychenko