How to use bytes from BitConverter.ToDouble

5

I have an interface that sends a reference value to a microcontroller. I need to send the values in bytes because these values will be stored in the memory of the microcontroller. In the interface, in C # I'm using for example:

double referencia = 125.6589;
byte[] byteArray = BitConverter.GetBytes(referencia);

Then I send this byteArray byte sequence. For the microcontroller.

But how can I use this byte sequence to reconstruct this reference value, what will I need to use in the microcontroller?

In the microcontroller I need to find a float:

float referencia = 125.6589;

Using that byte sequence to get this value. What mathematical operation I can use to get this value.

Obs. The microcontroller is a PIC, programmed in C.

    
asked by anonymous 14.10.2015 / 21:14

1 answer

6
The BitConverter uses the IEEE-754 format to represent the floating-point values, which is the format used by the C compilers to represent the values double (8 bytes) or float (4 bytes) . With this, you can convert the bytes you receive from BitConverter.GetBytes by using cast to the desired type. For example, your byteArray for the number you have equals the following bytes:

67,D5,E7,6A,2B,6A,5F,40

To see how I got these bytes, just print the value:

double referencia = 125.6589;
byte[] byteArray = BitConverter.GetBytes(referencia);
Console.WriteLine(string.Join(",", byteArray.Select(b => string.Format("{0:X2}", b))));

On the C side, you need to somehow get the bytes generated by BitConverter in your controller, and cast them to the corresponding type. Note that if you have 8 input bytes, you can not use float type in C (which has 4 bytes), you must use double .

char bytes[8];
bytes[0] = 0x67;
bytes[1] = 0xD5;
bytes[2] = 0xE7;
bytes[3] = 0x6A;
bytes[4] = 0x2B;
bytes[5] = 0x6A;
bytes[6] = 0x5F;
bytes[7] = 0x40;
double *d = (double *)bytes;
double referencia = *d;
printf("Valor: %lf\n", referencia);

Note that it is possible that the controller has a endianness other than the computer where the reference was generated (big vs. little endian), so you may have to reverse the byte order. When you take a test you will quickly know if this is the case or not.

    
14.10.2015 / 23:01