【急急急】二进制问题
如何把一个十进制转化成二进制。
然后把二进制指定的位置 进行置0或者置1
[解决办法]
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; } }}
[解决办法]
可以用扩展方法,读起来比较自然。
static class Int32Extension{ public static int SetBit(this int value, int bitIndex) { if( bitIndex < 0 || bitIndex > 31) throw new ArgumentOutOfRangeException(); return value | (1 << bitIndex); } public static int ClearBit(this int value, int bitIndex) { if (bitIndex < 0 || bitIndex > 31) throw new ArgumentOutOfRangeException(); return value & ~(1 << bitIndex); }}class Program{ static void Main(string[] args) { int i = 123; // i = 1111011 int j = i.ClearBit(0); // j = 1111010 int k = j.SetBit(0); // k = 1111011 }}