Android Question Bytes to Binary String

Discussion in 'Android Questions' started by nobbi59, Jun 13, 2019.

  1. nobbi59

    nobbi59 Active Member Licensed User

    Hi All,

    for a REST API i need to get a string from a byte array. The string must have the following format:

    \xc3\x8a\xc3\x85\x0e

    This is called 'binary' format in node.js but i couldnt find an equivalent in b4a, does anyone of you have an idea how to do this?
     
  2. DonManfred

    DonManfred Expert Licensed User

    Basically you can do:
    - Convert the bytes to HEX
    - Iterate through the HEX. Two Chars are one Byte.
    Outlput it with "\x[one hexpair]"
     
    nobbi59 and Erel like this.
  3. DonManfred

    DonManfred Expert Licensed User

    You also can try to use a map, add the bytearray to the map and then use jsongenerator to build the json from the map.
    Don´t know if it is compatible but i guess it should do the trick.
     
  4. Erel

    Erel Administrator Staff Member Licensed User

    Code:
    Sub Activity_Create(FirstTime As Boolean)
       
    Log(Convert("abcde"))
    End Sub

    Sub Convert(input As StringAs String
       
    Dim bc As ByteConverter
       
    Dim sb As StringBuilder
       sb.Initialize
       
    Dim hex As String = bc.HexFromBytes(input.GetBytes("utf8"))
       
    For i = 0 To hex.Length - 1 Step 2
           sb.Append(
    "\x").Append(hex.SubString2(i, i + 2))
       
    Next
       
    Return sb.ToString
    End Sub
     
    nobbi59 and DonManfred like this.
  5. nobbi59

    nobbi59 Active Member Licensed User

    Thanks Erel, this works :)
     
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