1

I have this 4 bytes : 0x41 0xCC 0xB7 0xCF and I must to find the number 25.5897503.

With Windev, a sample uses the Transfer() function but I can't find equivalent in C#

Could you help me with some indications ?

Thanks

Bob
  • 1,011
  • 3
  • 12
  • 28
  • 1
    Possible duplicate of [Efficiently convert byte array to Decimal](http://stackoverflow.com/questions/16979164/efficiently-convert-byte-array-to-decimal) – user1845593 May 05 '17 at 10:57

1 Answers1

4

It seems like a Single precision needed. So use ToSingle method in the BitConverter class:

byte[] array = new byte[] {0x41, 0xCC, 0xB7, 0xCF};
float value = BitConverter.ToSingle(array, 0);

Beware of Little / Big Endian though. If it doesn't work as expected, try to reverse the array first:

byte[] array = new byte[] {0x41, 0xCC, 0xB7, 0xCF};
Array.Reverse(array);
float value = BitConverter.ToSingle(array, 0);

EDIT:

Or, as Dimitry Bychenko suggested, you could also use BitConverter.IsLittleEndian to check the endianess of the converter:

byte[] array = new byte[] {0x41, 0xCC, 0xB7, 0xCF}; //array written in Big Endian
if (BitConverter.IsLittleEndian) //Reverse the array if it does not match with the BitConverter endianess
    Array.Reverse(array);
float value = BitConverter.ToSingle(array, 0);
Community
  • 1
  • 1
Ian
  • 30,182
  • 19
  • 69
  • 107
  • 1
    `BitConverter.IsLittleEndian` to check the actual endian (and *generalize* your solution): `float value = BitConverter.IsLittleEndian ? BitConverter.ToSingle(array.Reverse().ToArray(), 0) : BitConverter.ToSingle(array, 0);` – Dmitry Bychenko May 05 '17 at 11:14
  • @DmitryBychenko Thanks for the suggestion. I edited my answer with little modification for readability! ;) – Ian May 08 '17 at 03:20