日期:2014-05-18 浏览次数:20893 次
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace JinZhiTest { public partial class Form1 : Form { private int CurrBase = 10;//当前进制,开始默认为10 public Form1() { InitializeComponent(); } //转换成二进制 private void rdoEr_Click(object sender, EventArgs e) { this.JinZhiZhuHuan(CurrBase, 2); } //转换成八进制 private void rdoBa_Click(object sender, EventArgs e) { this.JinZhiZhuHuan(CurrBase, 8); } //转换成十进制 private void rdoShi_Click(object sender, EventArgs e) { this.JinZhiZhuHuan(CurrBase, 10); } //转换成十六进制 private void rdoShiLiu_Click(object sender, EventArgs e) { this.JinZhiZhuHuan(CurrBase, 16); } /// <summary> /// 进制转换 /// </summary> /// <param name="fromBase">原进制</param> /// <param name="toBase">目标进制</param> private void JinZhiZhuHuan(int fromBase, int toBase) { //得到文本框中数的十进制 int num = Convert.ToInt32(this.textBox1.Text.Trim(), fromBase); //将数转换成目标进制的字符串形式并显示在文本框中 this.textBox1.Text = Convert.ToString(num, toBase); //将目标进制保存为当前进制 this.CurrBase = toBase; }
------解决方案--------------------
十进制转换二进制string j = Convert.ToString(i, 2);
至于置0,你可以用Replace函数
------解决方案--------------------
int value = 100; string r = Convert.ToString(value, 2); Response.Write(r);
------解决方案--------------------
int x = 100; // 64(16) 1100100
如果想置第2位为1,则
x |= 0x0000010;
置0,则
x &= 0x1111011;
------解决方案--------------------
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace JinZhiTest { public partial class Form1 : Form { private int CurrBase = 10;//当前进制,开始默认为10 public Form1() { InitializeComponent(); } //转换成二进制 private void rdoEr_Click(object sender, EventArgs e) { this.JinZhiZhuHuan(CurrBase, 2); } //转换成八进制 private void rdoBa_Click(object sender, EventArgs e) { this.JinZhiZhuHuan(CurrBase, 8); } //转换成十进制 private void rdoShi_Click(object sender, EventArgs e) { this.JinZhiZhuHuan(CurrBase, 10); } //转换成十六进制 private void rdoShiLiu_Click(object sender, EventArgs e) { this.JinZhiZhuHuan(CurrBase, 16); } /// <summary> /// 进制转换 /// </summary> /// <param name="fromBase">原进制</param> /// <param name="toBase">目标进制</param> private void JinZhiZhuHuan(int fromBase, int toBase) { //得到文本框中数的十进制 int num = Convert.ToInt32(this.textBox1.Text.Trim(), fromBase); //将数转换成目标进制的字符串形式并显示在文本框中 this.textBox1.Text = Convert.ToString(num, toBase); //将目标进制保存为当前进制 this.CurrBase = toBase; } } }
------解决方案--------------------
可以用扩展方法,读起来比较自然。