Search code examples
c#windev

4 bytes to decimal - C# From Windev


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


Solution

  • 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);