简体   繁体   中英

How can I store two different values in a byte [] into two doubles? C#

I gather data from my BLE and i recieve it nicely. From my BLE i send my two different values like this:

String valueOne = String(5.56749);
String valueTwo = String(2.24759);
BTLEserial.print(valueOne);
BTLEserial.print(valueTwo);

I send it like two different strings.

And when I receive it in my C# code it is a byte [].

And this is how I succesfully recieve it with my C# code.

RXcharacteristics.ValueUpdated += (sender, e) =>
{
    var result = e.Characteristic.Value; //result is a System.Byte []
    var str = Encoding.UTF8.GetString(result, 0, result.Length);
    System.Diagnostics.Debug.WriteLine(str);
};

With that code I now get the two values stacked up underneath each other just like this in the log:

5.56749
2.24759

And that is maybe a little bit weird because in GetString(result, 0, result.Length); I have index as 0 which i thought would only get the first value so in my case I would only get 5.56749 in the log but I get them both.

What I now try to do is store them as unique doubles. I have started with something like this:

double valueOne;
double valueTwo;

valueOne = Convert.ToDouble(str.Split(' ').First());
valueTwo = Convert.ToDouble (str.Split(' ').Last());

But I get a crash: Input string was not in correct format on both valueOne and valueTwo .

I assume that I get it because the two different values are not seen as one string?

So what do I need to do in order to successfully store two values in my byte [] to doubles?

If you changed the data from the BLE to "1|value1" and "2|value2" you could use this:

        System.Diagnostics.Debug.WriteLine("Received: " + str);
        String[] s = str.Split(new char[] { '|' });
        int index = int.Parse(s[0]);
        if (index == 1) {
            valueOne = double.Parse(s[1], System.Globalization.CultureInfo.InvariantCulture);
        }
        else if (index == 2) {
            valueTwo = double.Parse(s[1], System.Globalization.CultureInfo.InvariantCulture);
        }
        System.Diagnostics.Debug.WriteLine(valueOne);
        System.Diagnostics.Debug.WriteLine(valueTwo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM