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

Representation of negative numbers in Hexadecimal format using C#

我一直卡在 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;
        }

请举例说明当温度为负值时从系统接收到的数据是什么,以及我应该如何修改函数以涵盖负温度情况。

假设系统使用 two's complement, you can use BitConverter.ToInt32 方法将温度作为 32 位有符号整数发送,将数组直接转换为有符号整数:

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;
    }