iOS Question How to Convert int to hex string

Scantech

Well-Known Member
Licensed User
Longtime User
In b4a I was using Bit.ToHexString.

How do i use it in b4i? Convert int to hex string.

Thank you
 
I don't have B4i installed any more, so this might be the blind leading the blind, but:

perhaps use ByteConverter library, although it looks like a two-stage process: first IntsToBytes and then HexFromBytes

1659179204321.png
 
Upvote 0
Just realised B4J will probably be a good-enough test:

B4X:
Dim bc As ByteConverter

Dim LeInt As Int = 12345678
Dim LeHex As String

LeHex = bc.HexFromBytes(bc.IntsToBytes(Array As Int(LeInt)))

Log(LeInt & " Dec = " & LeHex & " Hex")

1659180005696.png
 
Upvote 0
Just one problem. How do i get rid of leading 000000. if LeInt = 128 then hex = 00000080

I would have thought that for your application, fixed length strings that match the length of the register or field, would be preferable.

So maybe your 8-bit example would work better like:

B4X:
Dim bc As ByteConverter

Dim LeByte As Int = 128
Dim LeHex As String

LeHex = bc.HexFromBytes(Array As Byte(LeByte))

Log(LeByte & " Dec = " & LeHex & " Hex")
 
Last edited:
Upvote 1
Just one problem. How do i get rid of leading 000000. if LeInt = 128 then hex = 00000080

or maybe, if you know that only the lower 8 bits (2 hex digits) are relevant, use SubString to chop off the first 24 bits (6 hex digits):

B4X:
Dim bc As ByteConverter
    
Dim LeInt As Int = 128
Dim LeHex As String
    
LeHex = bc.HexFromBytes(bc.IntsToBytes(Array As Int(LeInt))).SubString(6)
    
Log(LeInt & " Dec = " & LeHex & " Hex")
 
Upvote 0
But if you really want to get rid of all leading hex zeroes and don't care about the resultant length, then run the full hex string through something like:

B4X:
Sub TrimLeadingZeroes(S As String)
 
    Dim StartFrom As Int = 0
 
    For I = 0 To S.Length - 2    'Length - 2 so that eg all zeroes "000" becomes "0" not ""
        If S.CharAt(I) = "0" Then
            StartFrom = I + 1
        Else
            Exit
        End If
    Next
 
    Return S.SubString(StartFrom)
 
End Sub

Bonus: works for decimal, octal and binary numeric strings too ?
 
Last edited:
Upvote 0
Back
Top