Domanda

I have serial communication between a computer and a sensor. When I request data from sensor. The sensor will reply two part of hex number. It is like "23 11". The first part is Most Significant bit which I have to multiply that value with 256. And the second part is Least Significant bit which that I don't have to multiply it. So, I want to split that character into 23 and 11. And multiply the first part. But I don't know how to identify the first and second part. So I can only multiply the first part and then sum them. I use this code to split the character :

string[] hexValuesSplit = hexValues.Split(new []{' '},StringSplitOptions.RemoveEmptyEntries);
È stato utile?

Soluzione

You are on the right track! The array returned from Split will have the MSB at index 0, and the LSB at index 1. You just need to convert those to bytes and you're good to go.

var values = hexValues.Split(new []{' '},StringSplitOptions.RemoveEmptyEntries);
if (values.Length != 2)
    throw new ArgumentException("Unexpected input format.");

var msb = Convert.ToByte(values[0]);
var lsb = Convert.ToByte(values[1]);

var result = (msb * 256) + lsb;

Altri suggerimenti

If your data just 23 11, hexValues.Split()[0] will give you 23. But if you have more data and you want to skip each second value then try this:

var values = hexValues.Split(new []{' '},StringSplitOptions.RemoveEmptyEntries)
            .Where((x, index) => index != 1 && index % 2 == 0)
            .Select(x => Convert.ToByte(x))
            .ToArray();

Sample input and output:

// input : 23 14 11 25 73 18 29 19
// output: 23 11 73 29  
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top