我编写了这段代码,用于在VB C#中将整数转换为十六进制数。 在运行代码时,按下转换按钮后,程序停止响应,我每次都必须使用任务管理器关闭它。我无法弄清楚它为什么会发生。有什么帮助吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public char value(byte x)
{
char[] arr = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
return arr[x];
}
public void IntToHex(int num)
{
string HexString=" ";
HexString = HexString.Trim();
while(num>=0)
{
HexString+=value((byte)(num%16));
num/=16;
}
HexText.Text += HexString;
HexText.Enabled = false;
Replay.Enabled = true;
Quit.Enabled = true;
}
public void ConvertButton_Click(object sender, EventArgs e)
{
Int32 Integer;
if (Int32.TryParse(IntegerText.Text, out Integer))
{
ConvertButton.Enabled = false;
IntToHex(Integer);
}
else
{
HexText.Text = "Invalid Input.";
}
}
public void Replay_Click(object sender, EventArgs e)
{
IntegerText.Text = null;
HexText.Text = null;
IntegerText.Enabled = true;
Replay.Enabled = false;
Quit.Enabled = false;
HexText.Enabled = false;
ConvertButton.Enabled = true;
}
public void Quit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
答案 0 :(得分:4)
为什么不使用
int num = 42;
string hex = num.ToString("X");
答案 1 :(得分:1)
似乎下面的函数有无限循环。
public void IntToHex(int num)
while(num>=0)
{
num/=16; // never set num smaller than 0
}