How to use Bitconverter.Todouble bytes

Asked

Viewed 65 times

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 saved in the memory of the microcontroller. On the interface, in C# I am using for example:

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

Then send this sequence of bytes "byteArray". To the microcontroller.

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

On the microcontroller I need to find a float:

float referencia = 125.6589;

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

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

1 answer

6


The BitConverter uses the IEEE-754 format to represent floating point values, which is the format used by C compilers to represent values double (8 bytes) or float (4 bytes). With this, you can convert the bytes you receive from BitConverter.GetBytes using a cast for 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 in 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 receive in your controller the bytes generated by BitConverter, and cast for the corresponding type. Note that if you have 8 bytes of input, you cannot use the type float in C (which has 4 bytes), 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 different from the computer where the reference was generated (big vs. little endian), so you may have to reverse the order of bytes. When you take a test you will quickly know whether this is the case or not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.