Android Question Formatting binary

Roger Daley

Well-Known Member
Licensed User
Longtime User
Hi All.

A simple question. Is there a simple way to format Binary numbers [String] in to groups of four digits to match Hexidecimal digits?
IE: 1011,1100,0010
NumberFormat2 does groups of three or none.

Regards Roger
 

LucaMs

Expert
Licensed User
Longtime User
This is not the best (also I'm not sure that you need exactly this :)):

B4X:
Log(BinaryFormat("101011011", 16))

' You can pass 0 if minimum length is not required.
Sub BinaryFormat(Binary As String, MinLength As Int) As String
    If Binary.Length = 0 Then Return ""

    Dim Res As String

Log("Binary : " & Binary)

    If Binary.Length < MinLength Then
        For i = 0 To MinLength - Binary.Length -1
            Binary = "0" & Binary
        Next
    End If

    Dim j As Int = 0
    For i = Binary.Length-1 To 0 Step -1
        Res = Binary.SubString2(i,i+1) & Res
        j = j + 1
        If j Mod 4 = 0 Then
            Res = " " & Res
        End If
    Next

    Return Res.Trim
End Sub
 
Last edited:
Upvote 0

Roger Daley

Well-Known Member
Licensed User
Longtime User
This is not the best (also I'm not sure that you need exactly this :)):

B4X:
Log(BinaryFormat("101011011", 16))

' You can pass 0 if minimum length is not required.
Sub BinaryFormat(Binary As String, MinLength As Int) As String
    If Binary.Length = 0 Then Return ""

    Dim Res As String

Log("Binary : " & Binary)

    If Binary.Length < MinLength Then
        For i = 0 To MinLength - Binary.Length -1
            Binary = "0" & Binary
        Next
    End If

    Dim j As Int = 0
    For i = Binary.Length-1 To 0 Step -1
        Res = Binary.SubString2(i,i+1) & Res
        j = j + 1
        If j Mod 4 = 0 Then
            Res = " " & Res
        End If
    Next

    Return Res.Trim
End Sub




Thanks LucaMs

Exactly what I needed.

Regards Roger

B4X:
Sub test_click
    Dim binnum As String
    Dim res As String
    Dim N As Int
    Dim Binlength As Int
    Dim Binstart As Int
    N = Rdisplay.Text        'Decimal number input
    binnum = Bit.ToBinaryString (N)    'NOTE: Creates very long string if negative number
    Binlength = binnum.Length
    Binstart = Binlength - Min(Binlength, 12)
    binnum = binnum.SubString2(Binstart, Binlength)  'Trims long string to 12 digits
    Binlength = binnum.Length
   
        'Adds comma every 4 digits
        Dim j As Int = 0
        For i = Binlength-1 To 0 Step -1
            res = binnum.SubString2(i,i+1) & res
            j = j + 1
            If j Mod 4 = 0 AND j Mod 12 <> 0 Then
                res = "," & res
            End If
        Next
        binnum = res

    Rdisplay.Text = binnum   'Binary number output formatted in to groups of four digits
End Sub
 
Upvote 0
Top