Android Question String of text to ASCII HEX string?

techknight

Well-Known Member
Licensed User
Longtime User
Question:

How do I convert a string into an ASCII HexString?

For example if I have

somestring = "012"

it becomes
hexstring = "303132" string representation of ASCII hex bytes. Without the LF and CR

thanks.
 

Roycefer

Well-Known Member
Licensed User
Longtime User
B4X:
Dim b() As Byte = "Hello".GetBytes("UTF8")
Dim ints(b.Length) As Int
For j =0 To b.Length-1
    ints(j) = b(j)
    Log(ints(j))
Next

This will Log() the decimal values of the ASCII bytes (note that ASCII is a subset of UTF-8). You can implement an easy "decimalToHex(dec as Int) as String" method to turn those decimal values into hex values.
 
Upvote 0

techknight

Well-Known Member
Licensed User
Longtime User
But.. I dont see where its turned into a hex string? Just a byte array?

I wouldnt need the Ints. Just some way to convert each byte into a string representation of the hex byte, thats NOT an array. but a single string.

I guess I would just need to use the Convert library.
 
Upvote 0

Roycefer

Well-Known Member
Licensed User
Longtime User
B4X:
Sub decimalToHex(dec As Int) As String
    Dim hexString As String
    Dim again As Boolean = True
    Do While again
        Dim hexdigit As Int = dec mod 16
        hexString = singleDigitToHex(hexdigit) & hexString
        dec = (dec-hexdigit)/16
        If dec<1 Then again = False
    Loop
    Return hexString
End Sub

Sub singleDigitToHex(dig As Int) As String
    If dig<10 Then Return dig
    If dig==10 Then Return "A"
    If dig==11 Then Return "B"
    If dig==12 Then Return "C"
    If dig==13 Then Return "D"
    If dig==14 Then Return "E"
    If dig==15 Then Return "F"
End Sub

The ByteConverter library could also do all that for you.
 
Upvote 0

techknight

Well-Known Member
Licensed User
Longtime User
I did it way easier using your first subroutine. Thanks for your insight.

B4X:
Sub TextToHexString(data As String) As String
Dim b() As Byte = data.GetBytes("UTF8")
Dim I As Int
Dim Str As String
Str = ""
For I=0 To b.Length-1
    Str = Str & Convert.HexFromBytes(b(I))
Next
Return Str
End Sub
 
Upvote 0

Roycefer

Well-Known Member
Licensed User
Longtime User
If you're using the ByteConverter library, you don't need to send HexFromBytes one Byte at a time. You can send it the whole array and it'll send you back the hex string all at once.

B4X:
Log(Convert.HexFromBytes("123".GetBytes("UTF8")))
 
Upvote 0
Top