B4R Question [SOLVED]How to convert string to hex with "0x"?

XorAndOr

Active Member
Licensed User
Hello to everyone

from android sending strings each one different
B4X:
TcpStreams.Write(ser.ConvertArrayToBytes(Array("B00000B02000C001")))'----> esp8266 server
in b4r I receive the string

B4X:
'RX from android
Sub AStream_NewData (Buffer() As Byte)

    Dim be(8) As Object
    
    Dim data() As Object = ser.ConvertBytesToArray(Buffer, be)
    
    Log(Buffer)
    
    
    For Each str As Object In data
    
        Log(str)'-----> B00000B02000C001 (this string I need to convert it in hex --> (0xB0, 0x00, 0x00, 0xB0, 0x20, 0x00, 0xC0, 0x01)
                
'        ............. ?
        
        
        
'        EXAMPLE : THIS HEX WORKS GOOD BUT IT IS A STATIC STRING HEX
'        Serial1.Stream.WriteBytes(Array As Byte(0xB0, 0x00, 0x00, 0xB0, 0x20, 0x00, 0xC0, 0x01), 0, 8)'----->uart tx
    next           

    
    
End Sub

and I should convert it to hexadecimal complete with "0x"
but I do not know how to do it.
Thanks for the suggestion
 

stevel05

Expert
Licensed User
You don't really want to convert them to strings as the data you are passing to the Serial.stream.WriteBytes method are Int Constants. Strings won't work the same.

You need to convert each byte pair to an Int, then pass those.

Something like:

B4X:
Dim S As String = "B00000B02000C001"
 
    Dim Vals(S.Length/2) As Int
    For i = 0 To S.Length - 1 Step 2
        Vals(i/2) = Bit.ParseInt(S.SubString2(i,i+2),16)
    Next
 
    Serial1.Stream.WriteBytes(Array As Byte(Vals(0), Vals(1), Vals(2), Vals(3), Vals(4), Vals(5), Vals(6), Vals(7)), 0, 8)
Making sure that the original string is the correct length.

Edit: I just realised this is a B4R question, I think it should work the same, I haven't used B4R.
 
Last edited:

XorAndOr

Active Member
Licensed User
Edit: I just realised this is a B4R question, I think it should work the same, I haven't used B4R.
thanks stevel05 for answering.
yes the question is for b4r.
I tried your code but b4r (S.lenght) does not accept it.
my string comes from android in object format and that's why I do not know how to do it.
 

stevel05

Expert
Licensed User
If it's definitely a string you can just cast it : Dim S As String = Obj
 

XorAndOr

Active Member
Licensed User
You don't really want to convert them to strings as the data you are passing to the Serial.stream.WriteBytes method are Int Constants.
yes, you're right, it's just what I needed.
I used your posted code to send from android, and in B4R I took int array values to send them to the BOSS GT-10 MIDI and everything works great.
Thank you!
 
Top