# Decimal to Binary Function

Email
 Submitted on: 10/15/2018 1:43:58 PM By: Paul Bahlawan Level: Beginner User Rating: By 1 Users Compatibility: VB 6.0 Views: 2153

A straightforward function to convert a decimal number to binary.Example: DecToBin(123) returns 01111011 and DecToBin(Asc("a")) returns 01100001

code:
Can't Copy and Paste this?
 ``` '************************************** ' Name: Decimal to Binary Function ' Description:A straightforward function to convert a decimal number to binary.Example: DecToBin(123) returns 01111011 and DecToBin(Asc("a")) returns 01100001 ' By: Paul Bahlawan '************************************** 'Decimal to Binary 'Returns a string representation of binary 'Paul Bahlawan Public Function DecToBin(dec As Integer) As String If dec = 0 Then DecToBin = "0" Else Do While dec <> 0 If dec Mod 2 = 0 Then DecToBin = "0" & DecToBin Else DecToBin = "1" & DecToBin End If dec = dec \ 2 Loop End If DecToBin = Format\$(DecToBin, "00000000") End Function ```

Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

What do you think of this code (in the Beginner category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

11/26/2018 6:37:07 AMRde

Hi Paul

Good demo, simple and does exactly what you say.
However, I saw the many string concatenations
which we know is very slow, and tried to come up
with a way without any string concatenation:

Function Dec2Bin(ByVal dec As Integer) As String
Dim idx As Integer
idx = 8
Dec2Bin = String\$(idx, "0")
Do Until dec = 0
Mid\$(Dec2Bin, idx) = CStr(dec Mod 2)
idx = idx - 1
dec = dec \ 2
Loop
End Function

Similar to what you had, but should be much faster.
Happy coding,
Rd :)

(If this comment was disrespectful, please report it.)

11/26/2018 6:42:09 AMRde

Sorry, should be
idx = 16
(If this comment was disrespectful, please report it.)

11/26/2018 6:44:25 AMRde

And of course your format code to
trim off all left hand zeroes

Happy coding :)
(If this comment was disrespectful, please report it.)

12/15/2018 5:32:45 PMPaul Bahlawan

Thats awsome RDE - I never thought to do it that way.
(If this comment was disrespectful, please report it.)