### Author Topic: MemToHex (and HexToMem) by SMcNeill  (Read 4053 times)

0 Members and 1 Guest are viewing this topic.

#### The Librarian

• Moderator
• Newbie
• Posts: 39
##### MemToHex (and HexToMem) by SMcNeill
« on: August 17, 2019, 11:50:23 pm »
MemToHex (and HexToMem)

Contributor(s): @SMcNeill
Source: qb64.org Forum
URL: https://www.qb64.org/forum/index.php?topic=1553.0
Tags: [hex] [mem]

Description:
With these, we can convert ANY memblock into a sequence of HEX values (which makes them excellent to paste into another program as DATA statements), and then we can take those hex values and convert them back into a memblock.

Source Code:
Code: QB64: [Select]
1. ' The string to be processed should have known length.
2. ' or:
3. ' Change 12 to a higher number and the HEX representation stores the trailing whitespace.
4. ' Trailing whitespace in an ordinary string can be truncated using RTRIM\$().
5. DIM TheString AS STRING * 12
6. TheString = "Hello World!"
7.
8. ' Prepare MEM block.
9. DIM m AS _MEM: m = _MEM(TheString)
10.
11. ' Convert string to HEX and print.
12. Hx\$ = MemToHex(m)
13. PRINT Hx\$
14.
15. ' Overwrite string.
16. TheString = "Overwritten?"
17. PRINT TheString
18.
19. ' Restore string from MEM and print the result.
20. HexToMem Hx\$, m
21. PRINT TheString; "..."
22. 'PRINT RTRIM\$(TheString); "..."
23.
24. ' Free the memblock (redundant at END but good practice).
25.
26. FUNCTION MemToHex\$ (m AS _MEM)
27.     s = ConvertOffset(m.SIZE) - 1
28.     FOR i = 0 TO s
29.         _MEMGET m, m.OFFSET + i, b
30.         h\$ = HEX\$(b)
31.         IF LEN(h\$) = 1 THEN h\$ = "0" + h\$
32.         MemToHex\$ = MemToHex\$ + h\$
33.
34. SUB HexToMem (hx\$, m AS _MEM)
35.     FOR i = 1 TO LEN(hx\$) STEP 2
36.         h = VAL("&H" + MID\$(hx\$, i, 2))
37.         _MEMPUT m, m.OFFSET + i \ 2, h
38.
39. FUNCTION ConvertOffset&& (value AS _OFFSET)
40.     DIM m AS _MEM 'Define a memblock
41.     m = _MEM(value) 'Point it to use value
42.     \$IF 64BIT THEN
43.         ' On 64 bit OSes, an OFFSET is 8 bytes in size. We can put it directly into an Integer64.
44.         _MEMGET m, m.OFFSET, ConvertOffset&& ' Get the contents of the memblock and put the values there directly into ConvertOffset&&.
45.         'However, on 32 bit OSes, an OFFSET is only 4 bytes. We need to put it into a LONG variable first.
46.         _MEMGET m, m.OFFSET, temp& ' Like this:
47.         ConvertOffset&& = temp& ' And then assign that long value to ConvertOffset&&.
48.     _MEMFREE m ' Free the memblock.
49.

« Last Edit: March 07, 2020, 01:19:18 am by The Librarian »