Pages

Saturday, May 18, 2013

Visual Basic 6.0: Convert from Decimal to Binary

In order to make this program we're going to use two textboxes txt_input and txt_output. And a Commandbuttton cmd_calculate.

The following is the complete code to make the program works:


Dim dec, bin As Integer
Dim out As String


Private Sub cmd_calculate_Click()

dec = Val(txt_input.Text)
out = ""


While dec > 0

bin = Fix(dec) Mod 2
dec = Fix(dec) / 2
out = bin & out
txt_output.Text = Val(out)

Wend

txt_output.SetFocus

End Sub

  


Code explanation:

Dim dec, bin As Integer: Here we declare the variables dec and bin as type integer.

Dim out As String: Here we declare the variable out as type string, it means just text.

dec = Val(txt_input.Text): We assign to the variable dec the value of the textbox txt_input while the function "Val" converts the textbox in integer type.

out = "": We initialize the variable out with an empty value.

While dec > 0: While the variable dec be greater than 0 then...

bin = Fix(dec) Mod 2: The variable "bin" value is going to be the variable "dec" Mod 2 value... The Mod is used to obtain the residue of a division. The division is going to be between the number we indicate next it, this case the number 2, by being the number 2 the base of the binary numbers.  

dec = Fix(dec) / 2:  After obtaining the first residue the variable "dec" is going to get itself value between 2. 

out = bin & out: The variable "out" value is going to be the variable "bin" value (the one that contains the division residue value) concatenate with the the same variable "out" to accumulate the value of the other residues generated while running the "WHILE".


txt_output.Text = Val(out) :  Finally we assign to the textbox txt_output the value of the variable "out".

Wend: Here is where the "WHILE" ends and returns up while the specified condition is met. 


*Notes: 

Funcion Val: Returns the contained numbers in a string as a number value of appropriate type.

Funcion Fix: Return the integer portion of a number.
& : Is used to concatenate characters. 

2 Comments: