Android Question Char = Int?

wonder

Expert
Licensed User
Longtime User
Why isn't it possible to perform arithmetic with chars and ints, without having to use the asc() function?
B4X:
'Not legal
Dim d = "d" As Char
Dim a = d - 3 As Int

'Legal
Dim d = "d" As Char
Dim a = asc(d) - 3 As Int

Isn't char a primitive type?
 

sorex

Expert
Licensed User
Longtime User
** Activity (main) Create, isFirst = true **
3431108 123456789
8888036 123456789
2707761 123456789
** Activity (main) Resume **


notice that the first and third are actually the same sub with just another name
 
Upvote 0

wonder

Expert
Licensed User
Longtime User
Well, here's the best I could come-up with:
B4X:
'Fast
Sub getInt(str As String) As Int
    Dim s = 0, v = 0, p = 1, i = str.Length - 1 As Int  
    Do While i > -1
        v = Asc(str.CharAt(i))
        If v = 45 Then
            s = -s
            Exit
        End If
        s = s + ((v - 48) * p)
        p = p * 10      
        i = i - 1      
    Loop
    Return s
End Sub

'Even faster
Sub getUnsignedInt(str As String) As Int
    Dim s = 0, p = 1, i = str.Length - 1 As Int
    Do While i > -1
        s = s + ((Asc(str.CharAt(i)) - 48) * p)
        p = p * 10
        i = i - 1
    Loop
    Return s
End Sub

Probably not really useful to anyone besides me...
 
Upvote 0

sorex

Expert
Licensed User
Longtime User
you could move the - check outside the loop.

before the loop to set the right length (0 or -1)

and after to make it negative or not

but that causes 'overhead' aswell but only once.
 
Upvote 0

wonder

Expert
Licensed User
Longtime User
Sure, why not? :)
B4X:
'Fast
Sub getInt(str As String) As Int
    Dim s = 0, z = 0, p = 1, i = (str.Length - 1) As Int
    If Asc(str.CharAt(0)) = 45 Then p = -1 Else z = -1
    Do While i > z
        s = s + ((Asc(str.CharAt(i)) - 48) * p)
        p = p * 10   
        i = i - 1   
    Loop
    Return s
End Sub
 
Upvote 0

MaFu

Well-Known Member
Licensed User
Longtime User
Funny that, for some reason Asc(str.CharAt(0)) == 45 is faster than str.CharAt(0) == "".
First is comparing two character codes, second is a string compare (more overhead).
 
Upvote 0
Top