【问题标题】:Converting int to Hex in C# WinForm [duplicate]在 C# WinForm 中将 int 转换为 Hex [重复]
【发布时间】:2021-12-26 18:47:26
【问题描述】:

所以我的课堂作业是让我们自己的算法不使用将 int 转换为十六进制的内置函数,并且在我的一生中它不会遵守。

我们文本中的示例将 24032 转换为 0x5DE0,但我得到的输出是 3210。

这是我的代码

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    List<string> errorList = new List<string>();
    List<int> hexList = new List<int>();
    string intInput = "";
    string msgOutput = "";

    private void btn_Hex_Click(object sender, EventArgs e)
    {
        intInput = box_Int.Text;
        int toHexFunc = Validator(intInput);
        ToHex(toHexFunc);
    }

    public void ToHex(int fromHexBtn)
    {
        int n = fromHexBtn;
        char[] hexNum = new char[100];
        int i = 0;
        while (n != 0)
        {
            int iterTemp = n % 16;

            // using ASCII table from https://www.dotnetperls.com/ascii-table
            if (iterTemp < 10)
            {
                hexNum[i] = (char)(iterTemp + 48);
                i++;
            }
            else
            {
                hexNum[i] = (char)(iterTemp + 55);
                i++;
            }

            n = n / 16;
        }

        for (int j = i - 1; j >= 0; j--)
        {
            hexList.Add(j);
        }

        msgOutput = String.Join("", hexList);
        lbl_Message.Text = msgOutput;

        
    }
}

    

【问题讨论】:

  • 这能回答你的问题吗? Convert integer to hexadecimal and back again
  • 不幸的是,这些解决方案使用内置转换器,并且底部较长的代码将字节转换为十六进制,这在这种情况下显然也没有用。我的必须是一个从头开始的新算法。
  • 可以看这里stackoverflow.com/questions/40322745/…了解算法
  • 为什么需要一个新的?
  • 这就是任务。该课程希望我们专注于使用循环和数组/列表,数据类型转换正是他们决定让我们做的事情。

标签: c# winforms hex


【解决方案1】:

基于此https://www.permadi.com/tutorial/numDecToHex/

class Program
{
    static void Main(string[] args)
    {
       var characters = "0123456789ABCDEF";

       int number = 24032;

       var hexidecimal = "";

       while (number > 0)
       {
          var remainder = number % 16;
          var res = Math.Abs(number / 16);

          hexidecimal = characters[remainder] + hexidecimal;

          number = res;
        }

        hexidecimal = "0x" + hexidecimal;

        WriteLine(hexadecimal);
   }
}

【讨论】:

  • 旁注:(供参考)var hexidecimal = $"0x{number:X}";当我们在现实生活中进行转换时
猜你喜欢
  • 2016-10-22
  • 2012-08-01
  • 2015-12-09
  • 2020-03-01
  • 2012-06-01
  • 2014-04-17
  • 2015-07-11
  • 2020-09-12
  • 2014-08-29
相关资源
最近更新 更多