Android Question Convert Code to B4A (Byte2Hex)

aaronk

Well-Known Member
Licensed User
Longtime User
Hi,

I have the following VB.net code and I want to be able to use it in B4A.

VB.net Code:
B4X:
Private Function Byte2Hex(ByRef b As Byte) As String
        Dim strTemp As String
        strTemp = Trim(Hex(b))
        While Len(strTemp) < 2
            strTemp = "0" & strTemp
        End While
        Byte2Hex = strTemp
    End Function

I have done the following but not sure if it's correct..

B4A Code:
B4X:
Sub Byte2Hex(b As Byte) As String
    Dim strTemp As String
        strTemp = b
    While strTemp.Length < 2
        strTemp = "0" & strTemp
    End While
   
    Byte2Hex = strTemp
End Sub

Have I converted it correctly ?
 

sorex

Expert
Licensed User
Longtime User
something like this might work

B4X:
Sub Byte2Hex(b As Int) As String
    Dim hex As String = "0123456789ABCDEF"
    Dim l,h As Int
    l=Bit.AND(b,0xf)
    h=Bit.ShiftRight(b,4)
    Return (hex.CharAt(h) & hex.CharAt(l))
End Sub

Edit: to make sure the input is a byte and not some large numer you better use this

B4X:
Sub Byte2Hex(b As Int) As String
    Dim hex As String = "0123456789ABCDEF"
    Dim l,h As Int
    l=Bit.AND(b,0xf)
    h=Bit.AND(Bit.ShiftRight(b,4),0xf)      ' <- safety fix
    Return (hex.CharAt(h) & hex.CharAt(l))
End Sub
 
Last edited:
Upvote 0
Top