Warm tip: This article is reproduced from serverfault.com, please click

floating point-使用C#以十六进制格式表示负数

(floating point - Representation of negative numbers in Hexadecimal format using C#)

发布于 2020-11-28 16:57:26

我陷入了C#WPF应用程序中数据格式转换的典型问题。我是C#的新手。我正在使用的GUI在从UDS消息获取字节数据后正在显示温度。当接收到的数据格式为41c00000(浮点格式)时,以下功能可以将数据转换为摄氏温度(正负)。

public static float ComposeFloat(List<string> list, bool bigEndian)
        {
            float val;
            byte[] payload = { 0, 0, 0, 0 }; // Used for float conversions

            // BitConverter needs a little endian list
            if (bigEndian)
            {
                list.Reverse();
            }
   
            for (int i = 0; i < 4; i++)
            {
                payload[i] = Convert.ToByte(list[i], 16);
            }
            
            val = BitConverter.ToSingle(payload, 0); // convert to an ieee754 float

            return val;
        }

但是对于我们系统中的其他温度传感器,UDS以00000028格式提供数据。由于UDS消息以整数格式提供温度,因此我修改了以下代码,如下所示,完全忽略了会发生什么情况如果温度为负,这是一个很大的错误。

public static float ComposeFloat_FromInt(List<string> list, bool bigEndian)
        {
            float val;
            int[] payload = { 0, 0, 0, 0 };
            if (bigEndian)
            {
                list.Reverse();
            }

           
            for (int i = 0; i < 4; i++)
            {
                    payload[i] = Convert.ToInt32(list[i], 16);
            }
            
            val = (float)payload[0];

            return val;
        }

请通过举一些例子来指导我,当温度为负值时从系统接收到的数据是什么,以及我应如何修改该功能以覆盖负温度的情况。

Questioner
Manu Chaudhary
Viewed
11
Arca Artem 2020-11-30 18:51:04

假设系统使用二进制补码将温度作为32位有符号整数发送,则可以使用BitConverter.ToInt32方法将数组直接转换为有符号整数:

public static int ComposeFloat_FromInt(List<string> list, bool bigEndian)
    {
        int val;
        byte[] payload = { 0, 0, 0, 0 };
        if (bigEndian)
        {
            list.Reverse();
        }

       
        for (int i = 0; i < 4; i++)
        {
                payload[i] = Convert.ToByte(list[i], 16);
        }
        
        val = BitConverter.ToInt32(payload, 0); // Converts a byte array to Int32

        return val;
    }