Create Decimal To Binary Converter - Easy Way by Custom Method in C#

Posted by ေတဇာလင္း Wednesday 31 August 2016 0 comments

မိတ္ေဆြ၊ ညီအစ္ကို၊ ေမာင္ႏွမအားလံုးပဲ မဂၤလာပါဗ်ာ။ ဒီေန႔ေတာ့ က်ေနာ္တို႔ Decimal Number တစ္ခုကို Binary String အျဖစ္ ဘရ္လို ေျပာင္းလဲ ယူႏိုင္မလဲဆိုတာေလးကို ေလ့လာၾကည့္ၾကမွာ ျဖစ္ပါတရ္။ Coding ေရးသားတဲ့အခါမွာ Visual Studio က ေထာက္ပံ့ေပးထားတဲ့ Method ေတြကို အသံုးမျပဳပဲ အလြယ္ကူဆံုးနည္းလမ္းတစ္ခုနဲ႔ ကိုယ္ပိုင္ Method တစ္ခု တည္ေဆာက္ၿပီး ေလ့လာၾကည့္ၾကမွာျဖစ္ပါတရ္။
Logic ပိုင္း ေထြေထြထူးထူးမရွိပါဘူး။ သာမာန္အေတြးကိုပဲ ရုပ္လံုးေဖာ္လုိက္တာပါ။ Coding Flow ေလးကို ၾကည့္ၾကည့္မရ္ဗ်ာ။ 
  1. Binary ေျပာင္းမွာျဖစ္တဲ့အတြက္ က်ေနာ္တို႔ ေျပာင္းလဲခ်င္တဲ့ Decimal ကို 2 နဲ႔စားမရ္။ 
  2. ရလာတဲ့ စားလဒ္(Quotient)ကို သုညနဲ႔မငယ္မခ်င္း Loop ပတ္ၿပီး ထပ္ခါတလဲလဲ 2 နဲ႔ စားေနမရ္။ 
  3. Loop ပတ္တိုင္း ရလာတဲ့ စားၾကြင္း(remainder)ကိုေတာ့ container array တစ္ခုထဲ ေခတၱထည့္သိမ္းထားမရ္ေပါ့။ 
  4. ေနာက္ဆံုး စားလဒ္(Quotient)ဟာ သုညနဲ႔ညီလွ်င္ပဲျဖစ္ျဖစ္၊ ငယ္သြားရင္ပဲျဖစ္ျဖစ္ Loop ကို ရပ္မရ္။ ဒီအခ်ိန္မွာေတာ့ စားၾကြင္း(remainder)ေတြႀကီး စုစည္းထားတဲ့ array တစ္ခုကို က်ေနာ္တို႔ ရရွိေနပါၿပီ။ 
  5. ေနာက္ဆံုးမွာေတာ့ ၄င္း Array ကို Invert လုပ္ ေျပာင္းျပန္လွန္ေပးျခင္းျဖင့္ Binary string တစ္ခုကို ဖန္တီးယူလိုက္တာပဲျဖစ္ပါတရ္။ နားလည္ႏိုင္ၾကလိမ့္မရ္လို႔ ထင္ပါတရ္ဗ်ာ။
Logic အနည္းငယ္စိမ္းေနမရ္ဆိုရင္ေတာ့..... http://programmingknowledge.blogspot.com/2014/07/6-number-system-conversions-from.html Pageမွာ ပံုနဲ႔တကြ ရွင္းထားတာေလး ရွိပါတရ္။ ေလ့လာၾကည့္ႏိုင္ပါတရ္ဗ်ာ။ အခုေတာ့ Coding အပိုင္းေလး ဆက္ၾကမရ္။ GUI ကိုေတာ့ က်ေနာ္ ေအာက္က ပံုစံအတိုင္း ပံုေဖာ္ထားပါတရ္။ မိတ္ေဆြတို႔ေတာ့ စိတ္ႀကိဳက္ ပံုေဖာ္ ဖန္တီးႏိုင္ပါတရ္။
Coding ေလးကို ေလ့လာၾကည့္လိုက္ၾကပါအံုးဗ်ာ။
using System;
using System; 
using System.Windows.Forms;   
namespace Converter 
{  
   public partial class frmDecToBinary : Form  
   {  
   public frmDecToBinary()  
   {  
      InitializeComponent();  
   }  
  
   public string DecToBinary(int Dec)   
   {  
      string remainder = null, result = null;  
      int Quotient = Dec;  
      while (Quotient > 0)  {  
         remainder += (Quotient % 2).ToString();   
         Quotient /= 2;  
      }   
  
      //Invert String  
      for (int i = remainder.Length - 1; i >= 0; i--)  {  
         result += remainder[i];  
      }  
      return result;   
   }   
 
   private void btnConvertDecToBi_Click(object sender, EventArgs e)  
   {   
      txtBinary.Text = DecToBinary(int.Parse(txtDecimal.Text));  
   } 
   
   private void btnReset_Click(object sender, EventArgs e)  
   {  
      txtDecimal.Text = "";  
      txtBinary.Clear();  
      txtDecimal.Focus();  
   }  
  } 
}   
ခက္ခက္ခဲခဲ ဘာမွ မရွိပါဘူးဗ်ာ။ Coding ေလးနဲ႔ ScreenShoot ေလးကို ၾကည့္လိုက္ရင္ေတာ့ မိတ္ေဆြတို႔အေနနဲ႔ ရွင္းျပစရာမလိုေလာက္ေအာင္ နားလည္သြားၾကလိမ့္မရ္လို႔ ထင္ပါတရ္ဗ်ာ။ မိတ္ေဆြအားလံုး ေလ့လာျခင္းျဖင့္ ေက်နပ္ႏိုင္ၾကပါေစဗ်ာ။

0 Responses so far.

Post a Comment