The following program will convert a decimal number (base 10) into it's binary representation (base 2).
To achieve it we need to create:
2 textboxes called txt_dec and txt_bin
1 button called btn_calculate
En el botón btn_calcular digitar el siguiente codigo:
int dec, bin;
string out = "";
dec = Convert.ToInt16(txt_dec.Text);
while (dec > 0)
{
bin = dec % 2;
dec = dec / 2;
Convert.ToString(bin);
out = bin + out;
txt_dec.Text = Convert.ToString(out);
}
txt_dec.Focus();
Code explanation:
int dec, bin: We declate the variable dec and bin Integer type.
string out = "": We declare the variable out type string which we'll assign the value 'nothing'.
dec = Convert.ToInt16(txt_dec.Text): Here we assign to the dec variable the textbox txt_dec value, at the same time we convert the textbx to Integer type.
while (dec > 0): While the variable dec be greater than 0 then ...
bin = dec % 2: The variable bin will get the value of the operation: the variable dec value % 2. (% means Mod in C#). The Mod is used to obtain a division residue. The division will be between the number we indicate next to the symbol %, this case the number 2, because 2 is the binary numbers base.
dec = dec / 2: After to obtain the first residue the variable dec will get it's own value between 2.
Convert.ToString(bin): We convert the variable bin into String type to achieve the concatenation.
out = bin + out: The variable "out" is going to get the bin's value (which contain the division residue) concatenated with the same variable "out" to keep accumulating the values of the others residues that generates while the "WHILE" runs.
txt_bin.Text = Convert.ToString(out):Finally we assign to the textbox txt_bin, the value of the variable "out".
0 Comments:
Post a Comment