B4R Question [SOLVED]Function Chr(AscII Code) simplification?

rwblinn

Well-Known Member
Licensed User
Longtime User
In B4R could not find a builtin function for Chr to convert an AscII DEC code to a Char literal (i.e. Chr(76) = 'L').

Workout a solution using Inline C combined with a Sub, but wondering if there is a simpler way for the Chr function. Any suggestions?

B4X:
Sub Process_Globals
    Public Serial1 As Serial
    Private asciiChar As String
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    Chr(76) 'L
    Chr(77) 'M
End Sub

' Convert ascii dec 48 (0) to 90 (Z)
' Runs inline c to update global var asciiChar
Private Sub Chr(asciiCode As Int)
    RunNative("convertAscII", asciiCode)
    Log(asciiCode, "=", asciiChar)
End Sub

#if c
// Convert ascii dec to b4r string using Arduino C/C++ function: char(x) - Converts a value to the char data type
// Requires global var asciichar as string
void convertAscII(B4R::Object* o) {
    String buffer = String(char(o->toULong()));
    B4R::PrintToMemory pm;
    B4R::B4RString* s = B4R::B4RString::PrintableToString(NULL);
    pm.print(buffer);
    B4R::StackMemory::buffer[B4R::StackMemory::cp++] = 0;
    b4r_main::_asciichar = s;
}
#End If
 

rwblinn

Well-Known Member
Licensed User
Longtime User
Many Thanks and advice in the next post by not using a sub

Removed the Sub as replaced by next post solution.
B4X:
'DO NOT USE
' Convert AscII DEC code to AscII String
' Example: <copy>
' Chr(76) returns "L"
' </copy>
Public Sub Chr(asciiCode As Int) As String
    Dim bc As ByteConverter
    Dim b() As Byte = Array As Byte(asciiCode)
    Return bc.StringFromBytes(b)
End Sub
 
Last edited:
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
I don't recommend using this sub too often...

Returning strings from subs can cause the stack buffer to be overflowed quite quickly.

1. Make 'bc' a global variable.
2. Prefer byte() over string.
3. If you must have a string for some reason then make it inline:
B4X:
Dim s As String = bc.StringFromBytes(Array As Byte(76))
 
Upvote 0

VigilanteDesign

New Member
Hi there, is this "stack buffer to be overflowed" meant only for B4R development? Thanks
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…