BitConverter.ToSingle truncates float values

Viewed 222

When converting binary data to float values using ruby's String#unpack method I get the following results:

[0x7d, 0xe8, 0x80, 0xc5].map(&:chr).join.unpack('e')[0]
# => -4125.06103515625

This is considered the correct result.

Using C# BitConverter.ToSingle method I get the following result:

var firstVal = BitConverter.ToSingle(new byte[] {0x7d, 0xe8, 0x80, 0xc5}, 0);
// firstVal: -4125.061

So it seems that the value is truncated somehow. Is there a way to extract the correct value (as in the ruby example) from the binary representation?

1 Answers

As I remember, Ruby only has one float type, and that is double-precision float. So the type of value of your ruby expression is double-precision float, analog of which in C# is "double". So if you want to get exact same number, you can do this (but I'm not sure it actually makes much sense, see @xanatos comment):

var firstVal = (double) BitConverter.ToSingle(new byte[] {0x7d, 0xe8, 0x80, 0xc5}, 0); 
// firstVal is -4125.06103515625
Related