Android Question [Solved] How can I convert this string (number) to int??

Dadaista

Active Member
Licensed User
Longtime User
Hi

I am not able to convert a string in to a number

The string is "0x416" and I want to convert into a int

This woks:
B4X:
Dim vendor As Int = 0x416

But I have the "number" in a text file. I read the "number" from text file but does not work

and this is the error
B4X:
java.lang.NumberFormatException: Invalid hex double:0x416

How can I solve it??

Thx in advance
 

Mahares

Expert
Licensed User
Longtime User
It is awful but by the moment works
Your code in Sub Hexa2Decimal (sNumber As String) As Int in pot #17 is wrong
B4X:
If sNumber.Contains("0x") Then
        sNumber = sNumber.SubString(3)   'WRONG
End If
It should be the below:
B4X:
If sNumber.Contains("0x") Then
        sNumber = sNumber.SubString(2)
End If
If you correct it, you will come up with 1046 which is what I gave you WayWayWay back in post #2. You really wore us out Mr. Dadaista. It should have not taken 20 posts for this thread. You are lucky, you have forum members that are very patient with you. You may also want to try the code Peter gave you in post #18. It does work also.
 
Last edited:
Upvote 0

Peter Simpson

Expert
Licensed User
Longtime User
You are lucky, you have forum members that are very patient with you. You may also want to try the code Peter gave you in post #18. It does work also.

Very lucky indeed. But saying that, this community is full of users of all development levels that are always willing to help if they can, and that includes every poster in this particular feed ;)

You are correct though, the last post should have been #3. #3 is where @Dadaista is thanking you for the working code :)
 
Upvote 0

Dadaista

Active Member
Licensed User
Longtime User
Your code in Sub Hexa2Decimal (sNumber As String) As Int in pot #17 is wrong
B4X:
If sNumber.Contains("0x") Then
        sNumber = sNumber.SubString(3)   'WRONG
End If

Well... there must be an space in the file that I read... I will write a
B4X:
.trim
:) before call the sub. I read the log... and #2 Failed and that is the reason #3 is the number

Very lucky indeed. But saying that, this community is full of users of all development levels that are always willing to help if they can, and that includes every poster in this particular feed ;)

Perhaps I am doing something wrong in the forum... I do not know. if that is so, I am sorry:(

As say @Peter Simpson my level in development and English too, is very low :(....I have serious problems to translate the posts... and for write post in english also

Thank to the forum I learn Development and english!!! :D:D:D it is great!!!.. I am kidding

This afternoon I will try to test the codes. I feel I am doing something wrong:oops:
 
Upvote 0

Dadaista

Active Member
Licensed User
Longtime User
Hi
Here we go again!!.. :p:p

First of all, the code.

Below the subs.. :)

B4X:
Sub Hexa2Decimal (sNumber As String) As Int
    Dim i, k As Int = 0
    Dim iSuma As Int = 0
    Dim sCar As String
    Dim iBase As Int = 1
   
    If sNumber.Contains("h") Then
        sNumber = sNumber.SubString2(0,sNumber.Length-1)
    End If
    If sNumber.Contains("0x") Then
        sNumber = sNumber.SubString(3) 'will be #~2
    End If
   
    For i = sNumber.Length -1 To 0 Step -1
        sCar = sNumber.CharAt(i)
        Select sCar
            Case "A", "a"
                sCar = "10"
            Case "B", "b"
                sCar = "11"
            Case "C", "c"
                sCar = "12"
            Case "D", "d"
                sCar = "13"
            Case "E", "e"
                sCar = "14"
            Case "F", "f"
                sCar = "15"
        End Select
        'If k = 0 Then iBase = 1
        If k = 1 Then iBase = 16
        If k = 2 Then iBase = 256
        If k = 3 Then iBase = 4096
        If k = 4 Then iBase = 65536
        If k = 5 Then iBase = 1048576
       
        iSuma = iSuma + (sCar * iBase)
        k = k + 1
    Next
    Return iSuma
End Sub

Sub PeterSimpsonHexa2Decimal(sNumber As String) As Int
    Dim BC As ByteConverter
    'Log($"Value ${BC.IntsFromBytes(BC.HexToBytes(sNumber.Replace("0x", "00000")))(0)}"$)    ' 1046
    Return BC.IntsFromBytes(BC.HexToBytes(sNumber.Replace("0x", "00000")))(0)
End Sub

Sub MaharesHexa2Decimal(sNumber As String) As Int
    'Dim strCC As String="0x416"
    Dim intCC As Int = Bit.ParseInt(sNumber.Replace("0x",""), 16)
    Return intCC  
End Sub

'endless...
Sub JAVAHexa2Decimal(sNumber As String) As Int
    Return jo.RunMethod("hex2decimal",Array(sNumber))
End Sub

private Sub jo As JavaObject
    Return Me
End Sub

#if java
import java.util.Scanner;

public static int hex2decimal(String s)
    {
             String digits = "0123456789ABCDEF";
           
             int val = 0;
             for (int i = 0; i < s.length(); i++)
             {
                 char c = s.charAt(i);
                 int d = digits.indexOf(c);
                 val = 16*val + d;
             }
             return val;
    }
#End If


Sub from @Peter Simpson Fails in this line
B4X:
BC.IntsFromBytes(BC.HexToBytes(sNumber.Replace("0x", "00000")))(0)

Log Says
B4X:
main_petersimpsonhexa2decimal (B4A line: 4846)
java.lang.Exception: hex string has odd number of characters
    at anywheresoftware.b4a.agraham.byteconverter.ByteConverter.HexToBytes(ByteConverter.java:254)
    at com.dbsaiz.caja.venta.free.main._petersimpsonhexa2decimal(main.java:9884)
    at com.dbsaiz.caja.venta.free.main._btnpnlprinter_click(main.java:2986)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:186)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:170)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:166)
    at anywheresoftware.b4a.objects.ViewWrapper$1.onClick(ViewWrapper.java:80)
    at android.view.View.performClick(View.java:4787)
    at android.view.View$PerformClick.run(View.java:19873)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)


Sub from @Mahares fails in this line
B4X:
Dim intCC As Int = Bit.ParseInt(sNumber.Replace("0x",""), 16)

log Says

B4X:
main_mahareshexa2decimal (B4A line: 4855)
Dim intCC As Int = Bit.ParseInt(sNumber.Replace("
java.lang.NumberFormatException: Invalid int: " 416"
    at java.lang.Integer.invalidInt(Integer.java:138)
    at java.lang.Integer.parse(Integer.java:410)
    at java.lang.Integer.parseInt(Integer.java:367)
    at anywheresoftware.b4a.keywords.Bit.ParseInt(Bit.java:86)
    at com.dbsaiz.caja.venta.free.main._mahareshexa2decimal(main.java:9712)
    at com.dbsaiz.caja.venta.free.main._btnpnlprinter_click(main.java:2986)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:186)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:170)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:166)
    at anywheresoftware.b4a.objects.ViewWrapper$1.onClick(ViewWrapper.java:80)
    at android.view.View.performClick(View.java:4787)
    at android.view.View$PerformClick.run(View.java:19873)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(Zyg

Java code also fails
log says

B4X:
JAVAHexaToDecimal Sub
---------------------
Hexadecimal:  0x416 ---------- Decimal: -1051626

0k... I am going to do...
B4X:
.trim
of the variable sNumber (holds the number)

Log says
PeterSimpsonHexaToDecimal Sub
----------------------------
Hexadecimal: 0x416 ---------- Decimal: 1046
----------------------------------------------------------------------

MaharesHexaToDecimal Sub
----------------------
Hexadecimal: 0x416 ---------- Decimal: 1046
----------------------------------------------------------------------

JAVAHexaToDecimal Sub
---------------------
Hexadecimal: 0x416 ---------- Decimal: -3050
----------------------------------------------------------------------

Dadaista Sub
----------------------------
Hexadecimal: 16 ---------- Decimal: 22

My sub returns an invalid decimal.... as @Mahares says... the line
B4X:
sNumber = sNumber.SubString(3)
is wrong.... I think Anybody can see it and that is the problem... data is wrong... I am very stupid.

I modify my sub... change #2 for #3 and log says
B4X:
PeterSimpsonHexaToDecimal Sub
────────────────────────────
Hexadecimal: 0x416 ---------- Decimal: 1046
══════════════════════════════════════════════════════════════════════
 
MaharesHexaToDecimal Sub
──────────────────────
Hexadecimal: 0x416 ---------- Decimal: 1046
══════════════════════════════════════════════════════════════════════
 
JAVAHexaToDecimal Sub
─────────────────────
Hexadecimal: 0x416 ---------- Decimal: -3050
══════════════════════════════════════════════════════════════════════
 
Dadaista Sub
────────────────────────────
Hexadecimal: 416 ---------- Decimal: 1046
══════════════════════════════════════════════════════════════════════

I do not know why the JAVAHexaToDecimal Sub, returns wrong number o_Oo_Oo_O

The problem was that I could not see the space between ":" and "0x" in this line from text file
B4X:
VendorId : 0x416

Below I Got the line from text file
B4X:
If sLinea.Contains("ProductId") Then
sP = sLinea.SubString(sLinea.IndexOf(":")+1)
End If

I did not check the spaces.... When I made the sub... the line
B4X:
sNumber = sNumber.SubString(3)
... smells....

"0x416" returns "0x4"... if "0x" is returned, something goes wrong :oops::oops:...

I am very stupid. The problem came from source data

I am very grateful for all members interesated in my problem.

Thank all members for your time!!:):):):):):) it was a silly problem.:oops::oops::oops::oops:



Regards all of you!!!!!!




Wow.... saturday night and I am writting post in forum... Something goes wrong... :D:D:D:D
 
Upvote 0

Peter Simpson

Expert
Licensed User
Longtime User
If you don't mind uploading your code, in the B4A IDE click on the File > Export As Zip whilst in your project, attach the zip file to your next post in this feed...
 
Last edited:
Upvote 0

Dadaista

Active Member
Licensed User
Longtime User
Oh.. I can not. Is big and with sensible information. I am sorry.

This is only a part of it. I only was trying read Vendorid and Productid from
B4X:
usb1.DeviceInfo(1)
to attach any POS printer to my app
 
Upvote 0

Mahares

Expert
Licensed User
Longtime User
I do not know why the JAVAHexaToDecimal Sub, returns wrong number o_Oo_O
The reason why you got -3050 instead of 1046 is because your string is "0x416" instead of "416". If you are starting with a string of "0x416", you need to remove the 0x or do something like this if you are USING inline Java:
Below is how you inline java call should be: The idea is to remove the 0x
B4X:
Dim strCC As Int =NativeMe.RunMethod("hex2decimal",    Array("0x416".Replace("0x","")))
 Log(strCC)  'displays 1046
If you are still having problems, please upload your project like Peter asked you to do. I am sure it will be solved.
 
Upvote 0

Peter Simpson

Expert
Licensed User
Longtime User
Hello @Dadaista,
You will find attached to this post a file that has what you are looking for already in a B4A project for you. Just download the attached zip file, unzip the file, load and run the file in B4A.

If you can't get it working after this then I will not be able to help you further as all the previously posted code in this thread/feed work as advertised.
 

Attachments

  • H2I.zip
    6.9 KB · Views: 287
Last edited:
Upvote 0

Dadaista

Active Member
Licensed User
Longtime User
Hi

The idea is to remove the 0x
You Are right!!!... I did not know that!!:oops:


Thank you so much to both @Mahares and @Peter Simpson . I really appreciate your help

This problem was solved!!!.... (delete the space at the beginning of the string solved it) But I have more problems...!!!:D:D:D new threads are coming.... :mad::mad::mad:


Regards!!
 
Last edited:
Upvote 0

sorex

Expert
Licensed User
Longtime User
you should read what the error is telling you...

main_mahareshexa2decimal (B4A line: 4855)
Dim intCC As Int = Bit.ParseInt(sNumber.Replace("
java.lang.NumberFormatException: Invalid int: " 416"

there's a leading space
 
Upvote 0
Hi

I am not able to convert a string in to a number

The string is "0x416" and I want to convert into a int

This woks:
B4X:
Dim vendor As Int = 0x416

But I have the "number" in a text file. I read the "number" from text file but does not work

and this is the error
B4X:
java.lang.NumberFormatException: Invalid hex double:0x416

How can I solve it??

Thx in advance


I don't know if you solve this problem but i found some bugs
this code i tested and everything is working very well.

B4X:
Sub btnConvert_Click
Public num As String
Public result As String

num = EditText1.Text
result = NumberFormat ( hexa2Decimal(num),0,2)
lsftView.AddSingleLine(result)
End Sub

Sub hexa2Decimal (sNumber As String) As Int
    Dim i, k As Int = 0
    Dim iSuma As Int = 0
    Dim sCar As String
    Dim iBase As Int = 1
 
    If sNumber.Contains("h") Then
        sNumber = sNumber.SubString(1)   // here you typed this sNumber.SubString2(0,sNumber.Length-1) when typed "h567" , errors
    End If
    If sNumber.Contains("0x") Then
        sNumber = sNumber.SubString(2)  '  here I changed to 2 you typed 3, index start a zero
    End If
 
    For i = sNumber.Length-1  To 0 Step -1
        sCar = sNumber.CharAt(i)
        Select sCar
            Case "A", "a"
                sCar = 10
            Case "B", "b"
                sCar = 11
            Case "C", "c"
                sCar = 12
            Case "D", "d"
                sCar = 13
            Case "E", "e"
                sCar = 14
            Case "F", "f"
                sCar = 15
        End Select
        'If k = 0 Then iBase = 1
        If k = 1 Then iBase = 16
        If k = 2 Then iBase = 256
        If k = 3 Then iBase = 4096
        If k = 4 Then iBase = 65536
        If k = 5 Then iBase = 1048576
  
        iSuma = iSuma + (sCar * iBase)
        k = k + 1
    Next
    Return iSuma
 
End Sub
all tested and working fine in my phone/tablet

I tried this: 0x567 = 1,383
h567 = 1,383
0xd3489ab5c = 29,993,820
hd3489ab5c = 29,993,820
 
Last edited:
Upvote 0
Top