简体   繁体   English

在 C# 中读取字节数组并转换为浮点数

[英]Reading byte array and converting into float in C#

I know there are many questions related to it but still they are not solving my problem.我知道有很多与之相关的问题,但它们仍然没有解决我的问题。 Below is my byte array:下面是我的字节数组:

截屏

As you can see that the byte is of 28 and each 4-byte value represents a single value ie I have a client machine which sent me 2.4 and while reading it, it is then converted into bytes.如您所见,字节为28 ,每个4-byte值代表一个值,即我有一台客户端机器向我发送2.4 ,在读取它时,它然后转换为字节。

//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.将每个 4 字节一一转换为十六进制,将它们保存在单独的变量中。 Like hex 1 = byte[0], hex2 = byte[1], hex3 = byte[2], hex4 = byte[3]..... hex28 = byte[27]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.组合 4 字节的十六进制值,然后将它们转换为浮点数,并为它们分配一个变量来保存浮点值。 Like v1 = Tofloat(hex1,hex2,hex3,hex4);v1 = Tofloat(hex1,hex2,hex3,hex4); // assuming ToFloat() is a function. // 假设 ToFloat() 是 function。

How can I achieve it?我怎样才能实现它?

Since you mentioned that the first value is 2.4 and each float is represented by 4 bytes;由于您提到第一个值为 2.4 并且每个浮点数由 4 个字节表示;

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:我们可以将字节分组为 4 字节块并将它们反转并将每个部分转换为浮点数,如下所示:

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:现在你有一个包含 7 个浮点数的数组:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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