|
Me encuentro escribiendo este artículo para todos aquellos que se vean en la necesidad de convertir un número a binario, les muestro dos formas diferentes de hacerlo. Los ejemplos que muestro a continuación utilizan el siguiente formulario: Los códigos son los siguientes: Vb.Net: Public Class Form1 Dim a() As String Dim n As Double Dim o As String Dim s As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try n = Convert.ToDouble(TextBox1.Text) s = "" While n > 0 If Val(n) Mod Val(2) = 1 Then s = s.Insert(0, "1") Else s = s.Insert(0, "0") End If n /= 2 o = Convert.ToString(n) a = o.Split(".") n = a(0) End While TextBox2.Text = s Catch o As Exception MessageBox.Show("Tines un error " + " " + o.Message) End Try End Sub End Class C# using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Conversiones { public partial class Form1 : Form { int n; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { n =Convert.ToInt32( textBox1.Text ); string s = ""; while ( n > 0 ){ s = ( n % 2 == 1) ? s.Insert(0, "1") : s.Insert(0, "0"); n /= 2; } textBox2.Text=s; } catch (Exception o) { MessageBox.Show("Tines un error " + " " + o.Message); } } } } Al final nuestro resultado seria el siguiente: Espero a alguien le halla servido .
|