0

试图取一个十进制值并将其转换为十六进制。这是 SCADA 程序中的 C# 脚本。以下将十六进制转换为十二月就好了:

using System;
using MasterSCADA.Script.FB;
using MasterSCADA.Hlp;
using FB;
using System.Linq;

public partial class ФБ : ScriptBase
{
    public override void Execute()
    {
    string hexValue = InVal;
    int num = Int32.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
    OutVal = num;   
    }
}

但是我遇到了相反的问题-当我尝试将 Dec 转换为 Hex 时。据我了解,以下应该可以工作,但它会给出错误:方法'ToString'没有重载在第12行采用'1'参数

11    int? decValue = InVal;
12        string hexValue = decValue.ToString("X");
13        //string hexValue = string.Format("{0:F0}", decValue);
14        uint num = uint.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
15        OutVal = num;

我可以通过使用第 13 行而不是第 12 行来避免该错误,但在这种情况下,我将 Hex 转换为 Dec 而不是 Dec 转换为 Hex。有人可以帮忙吗?

4

3 回答 3

1

您正在尝试调用ToString(string)一个int?值。Nullable<T>没有ToString(string)过载。你需要类似的东西:

string hexValue = decValue == null ? "" : decValue.Value.ToString("X");

(显然,根据您希望结果decValue为空的情况调整上述内容。)

于 2013-02-19T14:43:40.187 回答
0

这是我的功能:

using System;
using System.Collections.Generic;
class DecimalToHexadecimal
{

    static string DecToHex(decimal decim)
    {
        string result = String.Empty;

        decimal dec = decim;

        while (dec >= 1)
        {
            var remainer = dec % 16;
            dec /= 16;
            result = ((int)remainer).ToString("X") + result;
        }

        return result;
    }

    static void Main()
    {
        Console.WriteLine("Enter decimal");
        decimal dec = decimal.Parse(Console.ReadLine());
        Console.WriteLine("Hexadecimal representation to {0} is {1}", dec, DecToHex(dec));

        Console.ReadKey();
    }
}
于 2014-01-12T20:01:52.350 回答
0

试试decValue.Value.ToString("X"); 你的类型是int?和不是int

于 2013-02-19T14:43:18.620 回答