Share My Creation Binary 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: 967
  • convert.png
    convert.png
    12 KB · Views: 9,277

Stulish

Active Member
Licensed User
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:
 
Top