【问题标题】:Representation of negative numbers in Hexadecimal format using C#使用 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;
        }

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

【问题讨论】:

    标签: c# floating-point


    【解决方案1】:

    假设系统使用two's complement将温度作为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;
        }
    

    【讨论】:

    • 感谢 Arca 的帮助。我会在真实系统上测试你的代码。
    • 代码给出错误-无法在 val=BitConverter.ToInt32(payload,0) 行将 int[] 转换为 byte[]
    • 代码中需要进行一些编辑。 int[] payload={0,0,0,0,0} 替换为 byte[] payload={0,0,0,0} 和 payload[i]=Convert.ToInt32(list[i],16) 替换带有有效载荷[i]=Convert.ToByte(list[i],16)。谢谢@Arca。
    • 啊,复制/粘贴错误,抱歉!我已经将代码更新为从一开始就应该的样子。
    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 2011-10-02
    • 2014-11-30
    • 2021-12-18
    • 2015-02-11
    • 2013-01-09
    相关资源
    最近更新 更多