' The string to be processed should have known length.
' or:
' Change 12 to a higher number and the HEX representation stores the trailing whitespace.
' Trailing whitespace in an ordinary string can be truncated using RTRIM$().
DIM TheString AS STRING * 12
TheString = "Hello World!"

' Prepare MEM block.
DIM m AS _MEM: m = _MEM(TheString)

' Convert string to HEX and print.
Hx$ = MemToHex(m)
PRINT Hx$

' Overwrite string.
TheString = "Overwritten?"
PRINT TheString

' Restore string from MEM and print the result.
HexToMem Hx$, m
PRINT TheString; "..."
'PRINT RTRIM$(TheString); "..."

' Free the memblock (redundant at END but good practice).
_MEMFREE m
END

FUNCTION MemToHex$ (m AS _MEM)
    DIM b AS _UNSIGNED _BYTE
    s = ConvertOffset(m.SIZE) - 1
    FOR i = 0 TO s
        _MEMGET m, m.OFFSET + i, b
        h$ = HEX$(b)
        IF LEN(h$) = 1 THEN h$ = "0" + h$
        MemToHex$ = MemToHex$ + h$
    NEXT
END FUNCTION

SUB HexToMem (hx$, m AS _MEM)
    DIM i AS _INTEGER64
    DIM h AS _UNSIGNED _BYTE
    FOR i = 1 TO LEN(hx$) STEP 2
        h = VAL("&H" + MID$(hx$, i, 2))
        _MEMPUT m, m.OFFSET + i \ 2, h
    NEXT
END SUB

FUNCTION ConvertOffset&& (value AS _OFFSET)
    DIM m AS _MEM 'Define a memblock
    m = _MEM(value) 'Point it to use value
    $IF 64BIT THEN
        ' On 64 bit OSes, an OFFSET is 8 bytes in size. We can put it directly into an Integer64.
        _MEMGET m, m.OFFSET, ConvertOffset&& ' Get the contents of the memblock and put the values there directly into ConvertOffset&&.
    $ELSE
        'However, on 32 bit OSes, an OFFSET is only 4 bytes. We need to put it into a LONG variable first.
        _MEMGET m, m.OFFSET, temp& ' Like this:
        ConvertOffset&& = temp& ' And then assign that long value to ConvertOffset&&.
    $END IF
    _MEMFREE m ' Free the memblock.
END FUNCTION

$CHECKING:ON
