當前位置:編程學習大全網 - 編程軟體 - 編程實現各種進制數轉換,C#代碼

編程實現各種進制數轉換,C#代碼

其實 .net 類庫中提供了這壹類方法。例如:

Convert.ToInt32(String, Int32);

這裏面的 String 是需要轉換的數字, Int32 則是該數字的基數,例如:

Convert.ToInt32("FF", 16);

該語句將十六進制數 FF 轉換為十進制數 255 。

由此,可編寫壹個通用方法:

public string BaseConvert(string value, int from, int to)

{

int val = Convert.ToInt32(value, from);

return Convert.ToString(val, to);

}

value 為需要被轉換的數字, fromBase 為數字原來的形式, toBase 為需要被轉換成的形式。

編寫完方法後可以編寫實現代碼了,首先建立應用程序,添加四個單行文本框,需要對文本框做字符輸入的限制,例如十六進制數只能為 0~9, a~f, A~F, Back (最後壹個是退格鍵) ,那麽其對應的文本框的 KeyPress 事件為:

private void txtHex_KeyPress(object sender, KeyPressEventArgs e)

{

if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar >= 'A' && e.KeyChar <= 'F' || e.KeyChar >= 'a' && e.KeyChar <= 'f' || e.KeyChar == (char)Keys.Back) e.Handled = false;

else

e.Handled = true;

}

然後就是寫轉換代碼,對應的 TextChanged 事件:

private void txtHex_TextChanged(object sender, EventArgs e)

{

if (txtHex.Text.Length > 0)

{

txtDec.Text = ct.ConvertString(txtHex.Text, 16, 10);

txtBin.Text = ct.ConvertString(txtHex.Text, 16, 2);

txtOct.Text = ct.ConvertString(txtHex.Text, 16, 8);

}

else

{

txtDec.Text = "";

txtBin.Text = "";

txtOct.Text = "";

}

}

為避免不可預料的結果出現,代碼最好寫在 try catch 語句中以捕捉異常,最後編譯運行程序。

  • 上一篇:如何判斷孩子的邏輯思維能力
  • 下一篇:AI幫妳寫商品介紹文案用於種草推廣
  • copyright 2024編程學習大全網