0

I know there are many questions related to it but still they are not solving my problem. Below is my byte array:

screenshot

As you can see that the byte is of 28 and each 4-byte value represents a single value i.e. I have a client machine which sent me 2.4 and while reading it, it is then converted into bytes.

//serial port settings and opening it
        var serialPort = new SerialPort("COM2", 9600, Parity.Even, 8, StopBits.One);

        serialPort.Open();

        var stream = new SerialStream(serialPort);
        stream.ReadTimeout = 2000;
        // send request and waiting for response
        // the request needs: slaveId, dataAddress, registerCount            
        var responseBytes = stream.RequestFunc3(slaveId, dataAddress, registerCount);

        // extract the content part (the most important in the response)
        var data = responseBytes.ToResponseFunc3().Data;

What I want to do?

  1. Convert each 4 byte one by one to hex, save them In a separate variable. Like hex 1 = byte[0], hex2 = byte[1], hex3 = byte[2], hex4 = byte[3] ..... hex28 = byte[27]

  2. Combine 4-byte hex value and then convert them into float and assign them a variable to hold floating value. Like v1 = Tofloat(hex1,hex2,hex3,hex4); // assuming ToFloat() is a function.

How can I achieve it?

3
  • 3
    Do you mean something like: var bytes = new byte[] { 64, 25, 153, 154 }.Reverse().ToArray(); float value = BitConverter.ToSingle(bytes, 0);? Commented Apr 16, 2020 at 6:11
  • @Jimi, why is the call to .Reverse() necessary? Commented Apr 16, 2020 at 6:16
  • @simon-pearson Different endianness. The source is BigEndian (or just sent that way, it can be part of the protocol, it's usually documented). Of course, you can check BitConverter.IsLittleEndian to test the endianness of the current context. Commented Apr 16, 2020 at 6:24

1 Answer 1

3

Since you mentioned that the first value is 2.4 and each float is represented by 4 bytes;

byte[] data = { 64, 25, 153, 154, 66, 157, 20, 123, 66, 221, 174, 20, 65, 204, 0, 0, 65, 163, 51, 51, 66, 95, 51, 51, 69, 10, 232, 0 };

We can group the bytes into 4 byte blocks and reverse them and convert each part to float like:

int offset = 0;
float[] dataFloats =
    data.GroupBy(x => offset++ / 4) // group by 4. 0/4 = 0, 1/4 = 0, 2/4 = 0, 3/4 = 0 and 4/4 = 1 etc.
    // Need to reverse the bytes to make them evaluate to 2.4
    .Select(x => BitConverter.ToSingle(x.ToArray().Reverse().ToArray(), 0))
    .ToArray();

Now you have an array of 7 floats:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.