Binary Coded Decimal values use a binary pattern to represent the digits zero through nine. As Visual Basic does not use the BCD data type, it does not have a built-in function that converts BCD values to decimal values. However, you can program your own function that will accept input formatted as a BCD value and break it into four-bit nibbles, or chunks, and then convert those nibbles to a decimal number.

Type "Public Function BCD_to_int(ByVal input As Long)" to open your function. Use a smaller numerical data type instead of Long to save space if you know your program will not work with large numbers.

Type "Dim temp As Integer" and "Dim decNum as Integer" to declare two Integers in your function. Type "Dim strNum as String = """ to declare a string and initialise it with no text.

Type "While Not num = 0" to open a While loop that will repeat until the number the function receives becomes zero. Type "For I = 0 To 3" on the next line to begin a counted loop.

Type "temp = num Mod 10" and "num /= 10" on the following line. The first line will isolate the right-most digit of the BCD number and store it in your "temp" variable. The next line will shift the decimal of the BCD number to the left.

Type "If temp = 1 Then" to open a conditional check that determines whether your program needs to add to the value of your decimal number. Since you only need to add when "temp" equals one, do not include an "elseif" clause for temp equalling zero.

Type the following code in your "If" statement:

If temp = 1 Then

If I = 0 Then

ElseIf I = 1 Then

ElseIf I = 2 Then

ElseIf I = 3 Then

End If

End If

These conditions add the appropriate decimal value to your total based on which of the four bits in each nibble it checks. The "decNum" variable will hold the decimal value of the four-bit nibble.

Type "Next i" on the next line to tell your "For" loop to move to the next digit in the nibble. When your program has checked all four bits, it will have calculated the next digit of your decimal. Type "strNum = decNum & strNum" to append this value to the left-hand side of your string. Type "decNum = 0" to reset this variable before the next iteration of your while loop.

Type "End While" to close your While loop. Type "decNum = strNum" to force Visual Basic to convert the string holding your decimal value into an Integer and store it in the "decNum" variable. You can then manipulate this variable as needed. Type "Return decNum" to send the decimal value back to where your program called your function from. Type "End Function" to close the function.

## Most recent

- BCD numbers have eight bits. "0000 0000" represents zero and "0000 1001" represents nine. Since the four leftmost bits are zero, you do not need to consider them in your program. This saves space in memory and allows you to accept larger input numbers. If you want eight bit values for input, change your "For" loop to "For I = 0 to 7" to handle the extra load.