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

0 Members and 1 Guest are viewing this topic.

Offline 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.     NEXT
  34.  
  35. SUB HexToMem (hx$, m AS _MEM)
  36.     DIM i AS _INTEGER64
  37.     FOR i = 1 TO LEN(hx$) STEP 2
  38.         h = VAL("&H" + MID$(hx$, i, 2))
  39.         _MEMPUT m, m.OFFSET + i \ 2, h
  40.     NEXT
  41.  
  42. FUNCTION ConvertOffset&& (value AS _OFFSET)
  43.     DIM m AS _MEM 'Define a memblock
  44.     m = _MEM(value) 'Point it to use value
  45.     $IF 64BIT THEN
  46.         ' On 64 bit OSes, an OFFSET is 8 bytes in size. We can put it directly into an Integer64.
  47.         _MEMGET m, m.OFFSET, ConvertOffset&& ' Get the contents of the memblock and put the values there directly into ConvertOffset&&.
  48.     $ELSE
  49.         'However, on 32 bit OSes, an OFFSET is only 4 bytes. We need to put it into a LONG variable first.
  50.         _MEMGET m, m.OFFSET, temp& ' Like this:
  51.         ConvertOffset&& = temp& ' And then assign that long value to ConvertOffset&&.
  52.     $END IF
  53.     _MEMFREE m ' Free the memblock.
  54.  

screenshot.png
* MemToHex.bas (Filesize: 1.87 KB, Downloads: 390)
« Last Edit: March 07, 2020, 01:19:18 am by The Librarian »