Android Code Snippet Binary2String

Discussion in 'Code Snippets' started by ilan, Jan 5, 2018.

  1. ilan

    ilan Expert Licensed User

    Hi

    This is a snipped how to convert String to Binary and Binary to String.

    Thanks to @sorex for providing the Binary2String Code and to @Erel for the String2Binary Code.

    #1, String To Binary:

    Code:
    Sub String2Binary(txt As StringAs String
        
    Dim res As String = ""
        
    For Each b As Byte In txt.GetBytes("UTF8")
            
    Dim sb As StringBuilder
            sb.Initialize
            
    Dim x As Int = Bit.ShiftLeft(131)
            
    For i = 0 To 31
                
    Dim ii As Int = Bit.And(Bit.And(0xff, b), x)
                
    If ii <> 0 Then    sb.Append("1"Else    sb.Append("0")
                x = 
    Bit.UnsignedShiftRight(x, 1)
            
    Next
            res = res & 
    NumberFormat2(sb.ToString, 800False)' & " "
        Next
        
    Return res
    End Sub
    Use:
    Code:
    Dim bin As String = String2Binary(txt)
    #2, Binary To String:

    Code:
    Sub Binary2String(Bin As StringAs String
        
    Dim v As Int
        
    Dim data(Bin.Length/8As Byte
        
    For x=0 To Bin.Length-1
            
    If Bin.CharAt(x)="1" Then v=v+Power(2,(Bin.Length-x-1Mod 8)
            
    If x Mod 8=7 Then
                data(
    Floor(x/8))=v
                v=
    0
            
    End If
        
    Next
        
    Return BytesToString(data,0,data.Length,"UTF-8")
    End Sub
    Use:
    Code:
    Log(Binary2String(bin))
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice