在C#编程中,10进制转换为2进制、8进制和16进制源代码:
程序运行界面
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();
}
private void button1_Click(object sender, EventArgs e)
{
long sz;
string str = textBox1.Text;
if (long.TryParse(str, out sz))
{
switch(comboBox2.SelectedIndex)
{
case 0:
textBox2.Text = sz.ToString();
break;
case 1:
textBox2.Text = Convert.ToString(sz, 2);
break;
case 2:
textBox2.Text = Convert.ToString(sz, 8);
break;
case 3:
textBox2.Text = Convert.ToString(sz, 16);
break;
}
}
else
{
MessageBox.Show("请重新输入正确的数字", "提示");
}
}
}
}
结语:
学会使用Convert.ToString()方法来将10进制数转换为2进制、8进制和16进制。同时学会使用TryParse()数字传递方法,以及switch...case语句的用法。
喜欢的请关注、收藏!
最新评论