在 C# 中读取字节数组并转换为浮点数
Reading byte array and converting into float in C#
我知道有很多与之相关的问题,但它们仍然没有解决我的问题。下面是我的字节数组:
如您所见,该字节属于 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;
我想做什么?
将每4个字节一个一个地转换成十六进制,保存在一个单独的变量中。喜欢
hex 1 = byte[0], hex2 = byte[1], hex3 = byte[2], hex4 = byte[3]
..... hex28 = byte[27]
将4个字节的十六进制值合并,然后将它们转换为浮点数,并为其分配一个变量来保存浮点值。喜欢
v1 = Tofloat(hex1,hex2,hex3,hex4);
// 假设 ToFloat() 是一个函数。
如何实现?
既然你提到第一个值是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 };
我们可以将字节分组为 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();
现在你有一个包含 7 个浮点数的数组:
我知道有很多与之相关的问题,但它们仍然没有解决我的问题。下面是我的字节数组:
如您所见,该字节属于 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;
我想做什么?
将每4个字节一个一个地转换成十六进制,保存在一个单独的变量中。喜欢
hex 1 = byte[0], hex2 = byte[1], hex3 = byte[2], hex4 = byte[3] ..... hex28 = byte[27]
将4个字节的十六进制值合并,然后将它们转换为浮点数,并为其分配一个变量来保存浮点值。喜欢
v1 = Tofloat(hex1,hex2,hex3,hex4);
// 假设 ToFloat() 是一个函数。
如何实现?
既然你提到第一个值是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 };
我们可以将字节分组为 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();
现在你有一个包含 7 个浮点数的数组: