# Share My CreationBinary and Decimal Conversion

I have thrown together a binary/decimal conversion app as i needed to convert between the two and wondered if other people might also.

the code is below and i have attached the source in a ZIP file, i hope someone else finds it useful

B4X:
``````Sub decTobin(decVal As Int) As String
Dim bits As Int, dec2bin As StringBuilder
dec2bin.Initialize
Do While decVal > Power(2,bits)-1
bits=bits+1
Loop
For i =bits-1 To 0 Step -1
dec2bin.Append((Bit.and(decVal , Power(2,i)))/Power(2,i))
Next
Return dec2bin
End Sub
Sub binTodec(binVal As String) As Int
Dim i As Int, v As Int, dec As Int
i = binVal.Length
v = 1
For pos = i To 1 Step -1
If binVal.SubString2(pos-1, pos) = "1" Then dec = dec + v
v = v * 2
Next
Return dec
End Sub``````

#### Attachments

• convert.zip
7.2 KB · Views: 812
• convert.png
12 KB · Views: 9,003

#### Stulish

##### Active Member
Cnahne to decTobin sub

I found i needed the binary output to display 'x' number of digits, so if we were converting decimal 3 to binary but i wanted 6 bits then i wanted '000011' and not just the '11', so i have updated to implement that.

B4X:
``````Sub decTobin(decVal As Int,NumBit As Int) As String
Dim bits As Int, dec2bin As StringBuilder
dec2bin.Initialize
If NumBit=0 Then
Do While decVal > Power(2,bits)-1
bits=bits+1
Loop
Else
bits = NumBit
End If
For i =bits-1 To 0 Step -1
dec2bin.Append((Bit.and(decVal , Power(2,i)))/Power(2,i))
Next
Return dec2bin
End Sub
Sub binTodec(binVal As String) As Int
Dim i As Int, v As Int, dec As Int
i = binVal.Length
v = 1
For pos = i To 1 Step -1
If binVal.SubString2(pos-1, pos) = "1" Then dec = dec + v
v = v * 2
Next
Return dec
End Sub``````

one question is there a way to make a subroutine input optional for example:

Sub decTobin(num as Int, optional numOfbits as Int default=0) As String

This way if the second value is left empty than a default would be inserted???

Just a question from a :sign0104:

Thanks all for some great tips and code, i am just starting to get to grips with it all

Stu :sign0085:

#### Erel

##### B4X founder
Staff member
Optional parameters are currently not supported. Note that you can use NumberFormat or NumberFormat2 to set the minimum number of digits.

#### jcohedman

##### Member
How can I convert Dec to Bin, negative numbers?
Thank You!

#### Erel

##### B4X founder
Staff member
B4X:
``Log(Bit.ToBinaryString(-10))``

Android Question number conversions
Replies
4
Views
301
Android Code Snippet Number base conversions
Replies
7
Views
4K
Replies
6
Views
1K
B4A Library BigNumbers library
Replies
20
Views
11K
Replies
7
Views
11K