Your Federal Quarterly Tax Payments are due April 15th Get Help Now >>

program to convert binary to decimal by lindash

VIEWS: 20 PAGES: 2

									Program to Convert Binary to Decimal

We wish to write a program to convert a binary string such as 1011 into decimal (in this case the answer should be 11 (eleven) ).

Prelimaries: 1. Write some code to output the numbers 2, 4, 8, 16,…. 64. You may wish to use the function 2^i . (2 to the power of i). How would you get 1 as the first number? i.e. 1, 2, 4, 8, 16,…. 64.

2. Define a test string as below and write code to MsgBox the individual bits, from left to right one at a time. The output should be 1, 0, 1, 1, 1 Dim binSt As String, i As Integer, L As Integer binSt = "10111 L = Len(binSt) Now modify the code to output the bits from right to left rather than left to right. How will you generate the numbers 5, 4, 3, 2, 1? Use To L-i instead of To L ? Use Step -1? The output should be 1, 1, 1, 0, 1.

3. Incorporate techniques 1. and 2. above to write code to convert the binary string to decimal. (Dim dec As Integer to hold the result.)

D:\Docstoc\Working\pdf\94c9b190-1dd6-4b23-b024-bdf9b4cbb25d.doc

1

Program to convert a binary string to decimal: Private Sub CommandButton1_Click() Dim binSt As String, i As Integer, L As Integer Dim b As Integer, dec As Integer binSt = "10111": dec = 0 L = Len(binSt) For i = 1 To L b = Val(Mid(binSt, L - i + 1, 1)) dec = dec + b * 2 ^ (i - 1) Next i MsgBox dec End Sub

Exercise (home) o Write code to convert a 2 digit hex number to decimal. e.g A3 hex should be converted to 113 (one hundred and thirteen). Hints: To avoid lots of If statements and Case statements, you may wish to consider this: o Before you start your conversion you may wish to make sure that the characters are lowercase (or uppercase if you wish). o You may then wish to use the ASCII values of a, b,….f. Use the Asc() function to first determine these. o What are the ASCII values of 0 – 9? o What are the outputs of these? Msgbox (2 = 1) Msgbox (2 > 1) Msgbox (2 < 1) Msgbox CInt(2 < 1) Dim ha As Integer ha = 98 MsgBox CInt(ha >= 97 And ha <= 102) It should be possible to perform a hex to decimal conversion using one “formula” if we utilize the above techniques.

D:\Docstoc\Working\pdf\94c9b190-1dd6-4b23-b024-bdf9b4cbb25d.doc

2


								
To top