Android Question HEX number/string check

aaronk

Well-Known Member
Licensed User
Longtime User
Hello,

I am trying to check if a string length equals another number..

Lets say I have the following string: 0Dabcde12345678

Now I want to convert the first 2 digits of the string to a DEC number (0D = 13)
Then I want to check if the rest of the number length equals 13.

However, if the string equals 09123456789 then the 09 is already a DEC number as the rest of the string should equal 9. (123456789).

But if the string equals X812345678 then it will fail as the first 2 digits is not a valid hex or dec number. Anyone know how to check if the first 2 digits is a hex or dec number ?
 

NJDude

Expert
Licensed User
Longtime User
You could validate the hex number you entered, like this for example:
B4X:
Dim Test As String
Dim BadHex As Boolean

Test = "0Dabcde12345678"

For I = 0 To Test.Length - 1

    If Asc(Test.ToUpperCase.SubString2(I, I + 1)) > 70 OR Asc(Test.ToUpperCase.SubString2(I, I + 1)) < 48 Then
				
       BadHex = True

    End If

Next

If BadHex = True Then

   Msgbox("Bad Hex number", "")
			
Else

   Msgbox("OK", "")
			
End If
 
Upvote 0

LucaMs

Expert
Licensed User
Longtime User
B4X:
Sub HexToLong(HexStr As String) As Long
    Dim Lng As Long
    Dim Digit As String
    Dim DigitVal As Int

    For I = HexStr.Length -1 To 0 Step -1
        Digit = HexStr.SubString2(I, I+1).ToUpperCase
        If Not("0123456789ABCDEF".Contains(Digit)) Then
            ' not valid char
            Return -1
        End If

        If Digit.CompareTo("9") > 0 Then
            DigitVal = Asc(Digit) - 55
        Else
            DigitVal = Digit
        End If
        Lng = Lng + DigitVal * Power(16, HexStr.Length - 1 - I)
    Next

    Return Lng
End Sub
 
Last edited:
  • Like
Reactions: ung
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
Thanks heaps for both your help..
It has now helped me out and I can now use some of that code.
 
Upvote 0
Top