iOS Question Convert string to unicode

Hypnos

Active Member
Licensed User
Longtime User
Hi all,

I find the following code from B4A forum and I want to use it in my B4I project.
But seems "Bit.ToHexString" can't be use in B4I, can anyone teach me how to modify this code in order to use it in B4I please?

Thanks!

convert string to unicode:
Sub UnicodeEscape (s As String) As String
    
    Dim sb As StringBuilder
    sb.Initialize
    For i = 0 To s.Length - 1
        Dim u As String = Bit.ToHexString(Asc(s.CharAt(i)))
        sb.Append("\u")
        For i2 = 1 To 4 - u.Length
            sb.Append("0")
        Next
        sb.Append(u)
    Next
    Return sb.ToString

End Sub
 

Hypnos

Active Member
Licensed User
Longtime User
Thank you Johan! below is my new code but the output result is incorrect, do you have idea?

new code:
Sub UnicodeEscape (s As String) As String

    Dim sb As StringBuilder
    sb.Initialize
    For i = 0 To s.Length - 1
        Dim u As String
        Dim bc As ByteConverter
        u = bc.HexFromBytes(Array As Byte(Bit.ParseInt(Asc(s.CharAt(i)), 2)))
        sb.Append("\u")
        For i2 = 1 To 4 - u.Length
            sb.Append("0")
        Next
            sb.Append(u)
    Next
    return (sb.ToString)
End Sub
 
Upvote 0

hatzisn

Well-Known Member
Licensed User
Longtime User
You don't write what is wrong with this code but I think that bc.HexFromBytes returns a full hex string with a lot of precedenting zeros. Just strip the zeros in the beginning of the string (or select the right part of the string with 4 alphanumerics/digits - that is u = u.SubString2(u.Length-4, u.Length) - then there is no reason for the For-Next part).

Edit - Also the ", 2" why do you need it in Bit.ParseInt ? I believe the correct radix should be ", 10".

The code I believe should be (on the fly - not tested) something like this:

B4X:
Sub UnicodeEscape (s As String) As String

    Dim sb As StringBuilder
    sb.Initialize
    For i = 0 To s.Length - 1
        Dim u As String
        Dim bc As ByteConverter
        u = bc.HexFromBytes(Array As Byte(Bit.ParseInt(Asc(s.CharAt(i)), 10)))
        sb.Append("\u")
#IF B4A
        For i2 = 1 To 4 - u.Length
            sb.Append("0")
        Next
        sb.Append(u)
#ELSE IF B4i
        sb.Append(u.SubString2(u.Length-4, u.Length))
#END IF
    Next
    return (sb.ToString)
End Sub
 
Last edited:
Upvote 0

Hypnos

Active Member
Licensed User
Longtime User
Thanks hatzisn & Johan for the help! I'm not able to manage those bit/hex/radix well, so finally I use a lot of code lines to do the manual calculation to get the result. : )

 
Upvote 0

Similar Threads

Top