Saturday, February 7, 2009

十进制数转换为二进制,八进制,十六进制数的算法

更多精彩请到 http://www.139ya.com

转自: http://blog.csdn.net/gisfarmer/archive/2009/02/03/3860595.aspx


# using System;
# using System.Collections.Generic;
# using System.ComponentModel;
# using System.Data;
# using System.Drawing;
# using System.Text;
# using System.Windows.Forms;
#
# namespace ExDtoB
# {
# public partial class Form1 : Form
# {
# public Form1()
# {
# InitializeComponent();
# }
#
# //十进制转二制
# public string DtoB(int d)
# {
# string b = "";
# //判断该数如果小于2,则直接输出
# if (d < b =" d.ToString();" s =" 0;" n =" d;">= 2)
# {
# s++;
# n = n / 2;
# }
# int[] m = new int[s];
# int i = 0;
# do
# {
# c = d / 2;
# m[i++] = d % 2;
# d = c;
# } while (c >= 2);
# b = d.ToString();
# for (int j = m.Length - 1; j >=0; j--)
# {
# b += m[j].ToString ();
# }
# }
# return b;
# }
#
#
# //十进制转八进制
# public string DtoO(int d)
# {
# string o = "";
# if (d < o =" d.ToString();" s="0;" n="d;" temp =" d;">= 8)
# {
# s++;
# n = n / 8;
# }
# int[] m = new int[s];
# int i = 0;
# do
# {
# c = d / 8;
# m[i++] = d % 8;
# d = c;
# } while (c >= 8);
# o = d.ToString();
# for (int j = m.Length - 1; j >= 0; j--)
# {
# o += m[j];
# }
# }
# return o;
# }
#
#
# //十进制转十六进制
# public string DtoX(int d)
# {
# string x = "";
# if (d < x =" chang(d);" s =" 0;" n =" d;" temp =" d;">= 16)
# {
# s++;
# n = n / 16;
# }
# string [] m = new string[s];
# int i = 0;
# do
# {
# c = d / 16;
# m[i++] = chang(d % 16);//判断是否大于10,如果大于10,则转换为A~F的格式
# d = c;
# } while (c >= 16);
# x = chang(d);
# for (int j = m.Length - 1; j >= 0; j--)
# {
# x += m[j];
# }
# }
# return x;
# }
#
#
# //判断是否为10~15之间的数,如果是则进行转换
# public string chang(int d)
# {
# string x = "";
# switch (d)
# {
# case 10:
# x = "A";
# break;
# case 11:
# x = "B";
# break;
# case 12:
# x = "C";
# break;
# case 13:
# x = "D";
# break;
# case 14:
# x = "E";
# break;
# case 15:
# x = "F";
# break;
# default:
# x = d.ToString();
# break;
# }
# return x;
# }
#
# private void button1_Click(object sender, EventArgs e)
# {
# textBox2.Text = DtoB(Convert.ToInt32(textBox1.Text));//十转二进制
# }
#
# private void button2_Click(object sender, EventArgs e)
# {
# textBox2.Text = DtoO(Convert.ToInt32(textBox1.Text));//十转八进制
# }
#
# private void button3_Click(object sender, EventArgs e)
# {
# textBox2.Text = DtoX(Convert.ToInt32(textBox1.Text));//十转十六进制
# }
# }
# }

No comments: