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: 995
• convert.png
12 KB · Views: 9,308

Stulish

Active Member
Longtime User
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
Longtime User
Optional parameters are currently not supported. Note that you can use NumberFormat or NumberFormat2 to set the minimum number of digits.

jcohedman

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

Erel

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

Replies
2
Views
1K
Android Question number conversions
Replies
4
Views
1K
Replies
6
Views
2K
Replies
6
Views
1K
B4A Library BigNumbers library
Replies
20
Views
15K