首页 > 解决方案 > 使用 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;
        }

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

标签: c#floating-point

解决方案


假设系统使用二进制补码将温度作为 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;
    }

推荐阅读